<?php
/*
Plugin Name: Plugin 'Eshop'
Plugin URI: http://www.ondrejd.info/projects/wordpress-plugins/
Description: Simple but highly customizable eshop plugin for WordPress. Originally created for <a href="http://www.kingdvd.cz/">www.kingdvd.cz</a>.
Author: Ondrej Donek
Version: ##VERSION##
Author URI: http://www.ondrejd.info/
*/

/*  ***** BEGIN LICENSE BLOCK *****
    Version: MPL 1.1
    
    The contents of this file are subject to the Mozilla Public License Version 
    1.1 (the "License"); you may not use this file except in compliance with 
    the License. You may obtain a copy of the License at 
    http://www.mozilla.org/MPL/
    
    Software distributed under the License is distributed on an "AS IS" basis,
    WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
    for the specific language governing rights and limitations under the
    License.
    
    The Original Code is odCatalogWpPlugin.
    
    The Initial Developer of the Original Code is
    Ondrej Donek.
    Portions created by the Initial Developer are Copyright (C) 2010
    the Initial Developer. All Rights Reserved.
    
    Contributor(s):
    
    ***** END LICENSE BLOCK ***** */

// Include odWpPlugin
require_once realpath(dirname(__FILE__) . '/odWpPlugin.php');

/*
Long term todo:
TODO Umoznit nastaveni zda pouzit specialni registracni stranku ci defaultni WordPress. 
TODO Kontrolovat WordPress nastaveni 'users_can_register'.
*/

// Some constants
// TODO Should be moved to plugin's options!
define('OD_ESHOP_THUMB_SUFFIX_ORIGINAL', '_original.jpg');
define('OD_ESHOP_THUMB_SUFFIX_NORMAL', '_normal.jpg');
define('OD_ESHOP_THUMB_SUFFIX_SMALL', '_small.jpg');
define('OD_ESHOP_THUMB_HEIGHT_ORIGINAL', 450);
define('OD_ESHOP_THUMB_HEIGHT_NORMAL', 150);
define('OD_ESHOP_THUMB_HEIGHT_SMALL', 77);
define('OD_ESHOP_DEFAULT_MAIL_HEADERS', 'From: KingDVD.cz <info@kingdvd.cz>' . "\r\n");
define('OD_ESHOP_PAGER_ITEMS_LIMIT', 30);

// pChart is used, here are some constants.
define('OD_ESHOP_PCHART_DIR', dirname(__FILE__) . DIRECTORY_SEPARATOR . 'resources' . DIRECTORY_SEPARATOR . 'pChart-1.27' . DIRECTORY_SEPARATOR);
define('OD_ESHOP_PCHART_DEFAULT_FONT', OD_ESHOP_PCHART_DIR . 'tahoma.ttf');
define('OD_OD_ESHOP_PCHART_CACHE_DIR', dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR . 'eshop_cache' . DIRECTORY_SEPARATOR);

#{{{ odWpEshopPluginDbModel ---
if(!class_exists('odWpEshopPluginDbModel')):
#!src_obsolete_od-eshop-plugin-dbmodel##
endif;
#}}} --- odWpEshopPluginDbModel

#{{{ odWpEshopPluginRenderer ---
if(!class_exists('odWpEshopPluginRenderer')):
#!src_obsolete_od-eshop-plugin-renderer##
endif;
#}}} --- odWpEshopPluginRenderer

#{{{ odWpEshopPluginStats ---
if(!class_exists('odWpEshopPluginStats')):
#!src_obsolete_od-eshop-plugin-stats##
endif;
#}}} --- odWpEshopPluginStats

// Plugin's widgets

#{{{ odEshopNewestItemsWidget ---
if(!class_exists('odEshopNewestItemsWidget')):
#!src_widget_widget-newest_items##
endif;
#}}} --- odEshopNewestItemsWidget

#{{{ odEshopSearchformWidget ---
if(!class_exists('odEshopSearchformWidget')):
#!src_widget_widget-eshop_search##
endif;
#}}} --- odEshopSearchformWidget


/**
 * Main plugin object.
 * 
 * @author Ondrej Donek, <ondrejd@gmail.com>
 * @category odWpEshopPlugin
 * @version ##VERSION##
 */
class odEshopWpPlugin // TODO extends odWpPlugin
{
  static $plugin_id;
  static $version;
  static $textdomain;
    
  var $default_options = array(
      'eshop_images_dir' => 'wp-content/eshop_images/',
      'noimage_name' => 'noimage_normal.gif',
      'eshop_homepage_id' => 28,
      'eshop_main_page_id' => 24,
      'eshop_main_page_text_id' => 41,
      'eshop_detail_page_id' => 26,
      'eshop_basket_page_id' => 31,
      'eshop_search_results_page_id' => 7,
      'eshop_user_registration_page_id' => 11,
      'eshop_user_login_page_id' => 13,
      'eshop_contact_form_page_id' => 21,
      'after_login_redirect' => 'wp_default', // ['wp_default','wp_homepage','{valid url}']
      'enable_simple_user_admin' => true,
      'use_custom_login_stylesheet' => true,
      'custom_login_stylesheet' => 'custom_login.css',
      'eshop_stats_last_render_time' => null
  );
  
  /**
   * Constructor.
   * 
   * @return void
   */
  function odEshopWpPlugin()
  {
    // Set up the plugin
    odEshopWpPlugin::$plugin_id = 'od-eshop-plugin';
    odEshopWpPlugin::$version = '##VERSION##';
    odEshopWpPlugin::$textdomain = odEshopWpPlugin::$plugin_id;
    
    register_activation_hook(__FILE__, array(&$this, 'activate'));
    register_deactivation_hook(__FILE__, array(&$this, 'deactivate'));
    
    // Ensure that plugin's options are initialized
    $options = $this->get_options();
    // Ensure that exist's 'customer' user role
    $this->wp_user_roles();
    
    if(is_admin()) {
	    add_action('admin_menu', array(&$this, 'register_admin_menu'));
	    // XXX add_action('init', array(&$this, 'register_tinymce_buttons'));
    }
  
    // Filter for correct displaying single eshop pages
    // TODO This should be replaced by WP routes
    add_filter('the_content', array(&$this, 'content_filter'));
    
    // Initialize widgets
    add_action('widgets_init', array(&$this, 'init_widgets')); 
    
    // Customize redirect after user's login
    add_filter('login_redirect', array(&$this, 'custom_login_redirect'));
    
    // Use custom login stylesheet?
    if($options['use_custom_login_stylesheet'] == true) {
      add_action('login_head', array(&$this, 'custom_login_stylesheet'));
    }
  }

  /**
   * Activates the plugin
   * 
   * @returns void
   */
  function activate()
  {
    odWpEshopPluginDbModel::create_tables(self::$version);
  }
	
  /**
   * Returns WordPress user roles. Also insert eshop custom user role 'customer'
   * if not already present.
   * 
   * @todo OD: Here also we need to set up correct default role for newly registered users!
   * @return void
   */
  function wp_user_roles()
  {
    $user_roles = get_option('wp_user_roles');
    
    $need_update = false;
    
    if($user_roles == false) {
      // XXX Something is wrong - normal Wordpress user roles doesn't exists!
      wp_die('Something is wrong - normal Wordpress user roles doesn\'t exists!');
      return;
    }
    
    //if(!array_key_exists('customer', $user_roles)) {
      $user_roles['customer'] = array(
	  'name' => 'Zákazník',
	  'capabilities' => array(
	      'read' => 1,
	      'level_0' => 1
      ));
      
      $need_update = true;
    //}
	    
    if($need_update === true) {
      update_option('wp_user_roles', $user_roles);
    }
    
    return $user_roles;
  }

  /**
   * Deactivates the plugin
   * 
   * @returns void
   */
  function deactivate() { /* nothing to do ... */ }
  
  /**
   * Returns plugin's options
   *
   * @return array
   */
  function get_options() 
  {
    $options = get_option(self::$plugin_id . '-options');
    $need_update = false;

    if($options === false) {
      $need_update = true;
      $options = array();
    }

    foreach($this->default_options as $key => $value) {
      if(!array_key_exists($key, $options)) {
	$options[$key] = $value;
      }
    }

    if(!array_key_exists('latest_used_version', $options)) {
      $options['latest_used_version'] = self::$version;
      $need_update = true;
    }

    if($need_update === true) {
      update_option(self::$plugin_id . '-options', $options);
    }

    return $options;
  }
  
  /**
   * Changes page to where is user redirected after login
   * 
   * @param $content
   * @return unknown_type
   */
  function custom_login_redirect($content) 
  {
    $options = $this->get_options();
    
    $current_user = wp_get_current_user();
    if($current_user->has_cap('administrator')) {
      return $content;
    }
    
    if($options['after_login_redirect'] == 'wp_default') {
      return $content;
    }
    else if($options['after_login_redirect'] == 'wp_homepage') {
      return get_bloginfo('home');
    }
    else {
      // TODO Is valid URL?!
      return $options['after_login_redirect'];
    }
  }
	
  /** 
   * Appends custom stylesheet to the login page.
   * 
   * @return void
   */
  function custom_login_stylesheet() 
  {
    echo '<link rel="stylesheet" type="text/css" href="' . get_bloginfo('stylesheet_directory') . 
	 '/custom_login.css" />';
  }
  
  /**
   * Registers administration menu for the plugin
   * 
   * @returns void
   */
  function register_admin_menu() 
  {
    add_menu_page('Obchod',
		  'Obchod',
		  0,
		  self::$plugin_id,
		  array(&$this, 'admin_page'),
		  WP_PLUGIN_URL . '/' . self::$plugin_id . '/icon16.png');
    add_submenu_page(self::$plugin_id,
		     'Obchod - Přidej DVD',
		     'Přidej DVD',
		     0,
		     'od-eshop-plugin-edit',
		     array(&$this, 'edit_page'));
    add_submenu_page(self::$plugin_id,
		     'Obchod - Kategorie',
		     'Kategorie',
		     0,
		     'od-eshop-plugin-genre-categories',
		     array(&$this, 'genre_categories_page'));
    add_submenu_page(self::$plugin_id,
		     'Obchod - Cenové kategorie',
		     'Cenové kategorie',
		     0,
		     'od-eshop-plugin-prize-categories',
		     array(&$this, 'prize_categories_page'));
    add_submenu_page(self::$plugin_id,
		     'Obchod - Registrovaní uživatelé',
		     'Uživatelé',
		     0,
		     'od-eshop-plugin-users',
		     array(&$this, 'users_page'));
    add_submenu_page(self::$plugin_id,
		     'Obchod - Objednávky',
		     'Objednávky',
		     0,
		     'od-eshop-plugin-orders',
		     array(&$this, 'orders_page'));
    add_submenu_page(self::$plugin_id,
		     'Obchod - Statistiky (grafické)',
		     'Statistiky (grafy)',
		     0,
		     'od-eshop-plugin-stats',
		     array(&$this, 'stats_page'));
    add_submenu_page(self::$plugin_id,
		     'Obchod - Statistiky (textové)',
		     'Statistiky (textové)',
		     0,
		     'od-eshop-plugin-stats-text',
		     array(&$this, 'stats_page_text'));
    add_submenu_page(self::$plugin_id,
		     'Obchod - Dotazy',
		     'Dotazy',
		     0,
		     'od-eshop-plugin-faq',
		     array(&$this, 'faq_page'));
    add_submenu_page(self::$plugin_id,
		     'Obchod - Nastavení',
		     'Nastavení',
		     0,
		     'od-eshop-plugin-settings',
		     array(&$this, 'settings_page'));
  }
  
  /**
   * Initializes widgets
   * 
   * @return void
   */
  function init_widgets()
  {
    // XXX Create widgets!
    if(function_exists('register_widget')) {
      register_widget('odEshopNewestItemsWidget');
      register_widget('odEshopSearchformWidget');
    }
  }
  
  /**
   * Renders main admin page for the plugin
   * 
   * @returns void
   */
  function admin_page()
  {
		global $wpdb;
		
		$options = $this->get_options();
?>
		<div class="wrap">
			<div class="icon32">
			<img src="<?php echo WP_PLUGIN_URL . '/' . self::$plugin_id . '/icon32.png';?>"/>
			</div>
			<h2>Obchod</h2>
<?php
		if((isset($_POST['doaction']) || isset($_POST['doaction2']))) {
			$action = ($_POST['action'] != '-1') ? $_POST['action'] : $_POST['action2'];
			$items = (isset($_POST['items'])) ? $_POST['items'] : array();
			
			if(count($items) == 0) {
?>
			<div id="message" class="error fade"><p><strong>Nebyly označeny žádné položky.</strong></p></div>
<?php
			} else if($action == '-1' || $action == '-2') {
?>
				<div id="message" class="error fade"><p><strong>Nebyly označeny žádné položky.</strong>.</p></div>
<?php
			} else { // Possible actions: 'display','hide','delete'
				$query = '';
				switch($action) {
					case 'display': $query = "UPDATE `{$wpdb->prefix}eshop_items` SET `display` = '1' WHERE "; break;
					case 'hide'   : $query = "UPDATE `{$wpdb->prefix}eshop_items` SET `display` = '0' WHERE "; break;
					case 'delete' :
						$query = "DELETE FROM `{$wpdb->prefix}eshop_items` WHERE ";
						$query2 = "DELETE FROM `{$wpdb->prefix}eshop_items_to_genre_categories` WHERE ";
						break;
				}
				
				for($i=0; $i<count($items); $i++) {
					$query = $query . "`ID`='" . $items[$i] . "' " . ((($i+1)==count($items)) ? '' : 'OR ');
					
					if($action == 'delete') {
						$query2 = $query2 . "`item_ID`='" . $items[$i] . "' " . ((($i+1)==count($items)) ? '' : 'OR ');
					}
				}
				
				$res = $wpdb->query($query);
				
				if($action == 'delete') {
					$wpdb->query($query2);
				}
				
				if(!$res) {
					if($action == 'delete') {
?>
			  <div id="message" class="error fade"><p>Vyskytla se chyba. Položky nebyly smazány.</p></div>
<?php
					} else { 
?>
			  <div id="message" class="error fade"><p>Vyskytla se chyba. Položky nebyly aktualizovány.</p></div>
<?php
					}
				} else {
					$label = '';
					switch($action) {
						case 'display': $label = 'Zobrazeno položek: '; break;
						case 'hide'   : $label = 'Skryto položek: '; break;
						case 'delete' : $label = 'Smazáno položek: '; break;
					}
?>
			  <div id="message" class="updated fade"><p><?php echo $label;?><strong><?php echo $res;?></strong>.</p></div>
<?php
				}
			}
		}
		
		// Search
		$search = null;
		if(isset($_POST['dos'])) {
		  $search = $_POST['s'];
		  $do_search = true;
		}
		elseif(isset($_GET['dos'])) {
		  $search = $_GET['s'];
		  $do_search = true;
		}
		
		$pn = (isset($_POST['pn'])) ? $_POST['pn'] : ((isset($_GET['pn'])) ? $_GET['pn'] : null);
        $items_count = odWpEshopPluginDbModel::getEshopItemsCount(true, $search);
		$pager = new odWpEshopPluginPager($items_count, OD_ESHOP_PAGER_ITEMS_LIMIT, $pn);
		$pager->setUrlPrefix(get_bloginfo('home') . '/wp-admin/admin.php?page=od-eshop-plugin' . (($do_search == true) ? '&amp;dos=1&amp;s=' . $s : ''));
		$eshop_items = odWpEshopPluginDbModel::getEshopItems(OD_ESHOP_PAGER_ITEMS_LIMIT, $pager, true, $search);
		$i = 0;
?>
      <form action="<?php echo get_option('home');?>/wp-admin/admin.php?page=od-eshop-plugin" method="post" enctype="multipart/form-data">
        <div style="vertical-align: middle; float: right; width: 400px;">
          <label for="s"><strong>Vyhledávání:</strong></label>&nbsp;
          <input type="text" name="s" value="<?php echo $search;?>"/>
          <input type="submit" value="Vyhledat" name="dos" class="button-secondary action"/>
        </div>
      </form>
      <div style="clear: both;"> &nbsp;</div>
	  <form action="<?php echo get_option('home');?>/wp-admin/admin.php?page=od-eshop-plugin" method="post" enctype="multipart/form-data">
		<input type="hidden" name="pn" value="<?php echo $pager->mCurrentPage;?>"/>
		<div class="tablenav">
		  <div class="alignleft actions">
			<select name="action" class="select-action">
			  <option value="-1" selected="selected">Vyber akci</option>
				<option value="display">Zobrazit</option>
				<option value="hide">Skrýt</option>
				<option value="-2">-----</option>
			  <option value="delete">Smazat</option>
			</select>
			<input type="submit" value="Provést" name="doaction" id="doaction" class="button-secondary action" />
    	  </div>
          <div class="alignright actions">
            <?php if($pager->mCurrentPage == 1):?>
            &lt; předchozí
            <?php else:?>
            <a href="<?php echo $pager->getPreviousPageUrl();?>">&lt; předchozí</a>
            <?php endif;?> 
            (stránka <strong><?php echo $pager->mCurrentPage;?></strong>/<?php echo $pager->mTotalPagesCount;?>)
            <?php if($pager->mCurrentPage < $pager->mTotalPagesCount):?>
            <a href="<?php echo $pager->getNextPageUrl();?>">následující &gt;</a>
            <?php else:?>
            následující &gt;
            <?php endif;?>
          </div>
		  <br class="clear" />
		</div>
		<div class="clear"></div>
		<table class="widefat post fixed" cellspacing="0">
		  <thead>
			<tr>
			  <th scope="col" style="width: 5%;" class="manage-column column-cb check-column"><input type="checkbox" /></th>
			  <th scope="col" style="width:10%;" class="manage-column column-cb">Číslo DVD</th>
			  <th scope="col" style="width:28%;" class="manage-column column-cb">Název</th>
			  <th scope="col" style="width:20%;" class="manage-column column-cb">Kategorie</th>
			  <th scope="col" style="width:17%;" class="manage-column column-cb">Cenová skupina</th>
			  <th scope="col" style="width:10%;" class="manage-column column-cb">Zobrazit</th>
			</tr>
		  </thead>
		  <tfoot>
			<tr>
			  <th scope="col" style="width: 5%;" class="manage-column column-cb check-column"><input type="checkbox" /></th>
			  <th scope="col" style="width:10%;" class="manage-column column-cb">Číslo DVD</th>
			  <th scope="col" style="width:28%;" class="manage-column column-cb">Název</th>
			  <th scope="col" style="width:20%;" class="manage-column column-cb">Kategorie</th>
			  <th scope="col" style="width:17%;" class="manage-column column-cb">Cenová skupina</th>
			  <th scope="col" style="width:10%;" class="manage-column column-cb">Zobrazit</th>
			</tr>
		  </tfoot>
		  <tbody id="the-list" class="list:odeshop">
			<?php foreach($eshop_items as $eshop_item):?>
		    <tr class="<?php echo (($i++ % 2) ? 'alternate' : '' ) ;?> status-inherit">
				<th scope="row" class="check-column"><input type="checkbox" name="items[]" value="<?php echo $eshop_item['item_ID'];?>"/></th>
				<td><?php echo $eshop_item['item_shopno'];?></td>
				<td><a href="<?php echo get_bloginfo('home');?>/wp-admin/admin.php?page=od-eshop-plugin-edit&amp;itemid=<?php echo $eshop_item['item_ID'];?>"><?php echo $eshop_item['item_title'];?></a></td>
				<td><?php echo $eshop_item['genre_categories'];?></td>
				<td><?php echo $eshop_item['prize_category'];?></td>
				<td><?php echo ($eshop_item['item_display'] == '1') ? '<span style="color:green;">ano</span>' : '<span style="color:#f30;">ne</span>';?></td>
			</tr>
			<?php endforeach;?>
		  </tbody>
		</table>
		<div class="tablenav">
		  <div class="alignleft actions">
				<select name="action2" class="select-action">					
					<option value="-1" selected="selected">Vyber akci</option>
					<option value="display">Zobrazit</option>
					<option value="hide">Skrýt</option>
					<option value="-2">-----</option>
					<option value="delete">Smazat</option>
				</select>
				<input type="submit" value="Provést" name="doaction2" id="doaction2" class="button-secondary action" />
		  </div>
          <div class="alignright actions">
            <?php if($pager->mCurrentPage == 1):?>
            &lt; předchozí
            <?php else:?>
            <a href="<?php echo $pager->getPreviousPageUrl();?>">&lt; předchozí</a>
            <?php endif;?> 
            (stránka <strong><?php echo $pager->mCurrentPage;?></strong>/<?php echo $pager->mTotalPagesCount;?>)
            <?php if($pager->mCurrentPage < $pager->mTotalPagesCount):?>
            <a href="<?php echo $pager->getNextPageUrl();?>">následující &gt;</a>
            <?php else:?>
            následující &gt;
            <?php endif;?>
          </div>
		  <br class="clear" />
		</div>
	  </form>
	</div>
<?php 
  }
	
  /**
   * Renders form for adding/editing single eshop item.
   * 
   * @returns void
   */
  function edit_page()
  {
		global $wpdb;
		
		$options = $this->get_options();
		$mode = (isset($_GET['itemid'])) ? 'edit' : 'add';
		$itemid = ($mode == 'edit') ? $itemid = (int) $_GET['itemid'] : null;
		
		if(isset($_POST['saveediteditem'])) {
			$mode             = $_POST['mode'];
			$itemid					= ($mode == 'edit') ? $_POST['itemid'] : null;
			$shopno           = $_POST['shopno'];
			$title            = $_POST['title'];
			$title_orig       = $_POST['title_orig'];
			$image            = '';
			$_image           = $_FILES['file_img'];
			$genre_categories = $_POST['genre_categories'];
			$director         = $_POST['director'];
			$actor            = $_POST['actor'];
			$language         = $_POST['language'];
			$subtitles        = $_POST['subtitles'];
			$custom           = $_POST['custom'];
			$prize_category   = $_POST['prize_category'];
			$display          = (isset($_POST['display'])) ? '1' : '0';
			
			if(!is_array($genre_categories)) {
?>
		<div class="updated fade">
			<p><strong>Nepřiřadili jste obrázek do žádné z kategorií!</strong></p>
		</div>
<?php
			}
			
			// Upload and resize thumbnail image
			if(!empty($_image['name'])) {
				if(!($image = $this->_upload_image($_image))) {
?>
		<div id="message" class="error fade">
		  <p><strong>Obrázek nebyl úspěšně nahrán na server!</strong></p>
		</div>
<?php
				}
				
				$image = (!$image) ? '' : $image;
			}
			
			if($mode == 'add') {
				$query = "
						INSERT INTO `{$wpdb->prefix}eshop_items` 
							( `ID` ,
								`shopno` ,
								`title` ,
								`title_orig` ,
								`image` ,
								`director` ,
								`actor` ,
								`language` ,
								`subtitles` ,
								`custom` ,
								`prize_category_ID` ,
								`created` ,
								`display` )
						VALUES
							( NULL,
								'{$shopno}' ,
								'{$title}' ,
								'{$title_orig}' ,
								'{$image}' ,
								'{$director}' ,
								'{$actor}' ,
								'{$language}' ,
								'{$subtitles}' ,
								'{$custom}' ,
								'{$prize_category}' ,
								CURRENT_TIMESTAMP ,
								'{$display}' ) ";
				
				$res = $wpdb->query($query);
				$_itemid = $wpdb->insert_id;
				
				if(is_array($genre_categories)) {
					foreach($genre_categories as $genre_category) {
						$query = "
								INSERT INTO `{$wpdb->prefix}eshop_items_to_genre_categories` ( `item_ID` , `genre_category_ID` ) 
								VALUES ( '{$_itemid}' , '{$genre_category}' ) ";
						$wpdb->query($query);
					}
				}
?>
				<div id="message" class="updated fade">
					<p><strong>Byla úspěšně vytvořena položka s ID <code><?php echo $_itemid;?></code>.</strong></p>
				</div>
<?php
			} else {
				$query = "DELETE FROM `{$wpdb->prefix}eshop_items_to_genre_categories` WHERE `item_ID` = '{$itemid}' ";
				$wpdb->query($query);
				
				$query = "
						UPDATE `{$wpdb->prefix}eshop_items`
						SET
								`shopno` = '{$shopno}' ,
								`title` = '{$title}' , 
								`title_orig` = '{$title_orig}' , " . ((!empty($_image['name'])) ? "
								`image` = '{$image}' ," : "") . "
								`director` = '{$director}' ,
								`actor` = '{$actor}' ,
								`language` = '{$language}' ,
								`subtitles` = '{$subtitles}' ,
								`custom` = '{$custom}' ,
								`prize_category_ID` = '{$prize_category}' , 
								`display` = '{$display}'  
						WHERE `ID` = '{$itemid}' ";
				$wpdb->query($query);
				
				if(is_array($genre_categories)) {
					foreach($genre_categories as $genre_category) {
						$query = "
								INSERT INTO `{$wpdb->prefix}eshop_items_to_genre_categories` ( `item_ID` , `genre_category_ID` ) 
								VALUES ( '{$itemid}' , '{$genre_category}' ) ";
						$wpdb->query($query);
					}
				}
?>
				<div id="message" class="updated fade">
					<p><strong>Položka s ID <code><?php echo $itemid;?></code> byla úspěšně aktualizována.</strong></p>
				</div>
<?php
			}
		}
?>

		<div class="wrap">
			<div class="icon32">
			<img src="<?php echo WP_PLUGIN_URL . '/' . self::$plugin_id . '/icon32.png';?>"/>
			</div>
			<?php if($mode == 'add'):?>
			<h2>Obchod - Přidej DVD</h2>
			<?php elseif($mode == 'edit'):?>
			<h2>Obchod - Edituj DVD #<?php echo $itemid;?></h2>
			<?php endif;?>
<?php
		$item = null;
		if($mode == 'edit') {
			$mode = 'edit';
			$item = odWpEshopPluginDbModel::getEshopItemById($itemid);
		}
?>
			<?php if(!$item && $mode == 'edit'):?>
				<p><strong>Vyskytla se chyba! Nemohu editovat položku s daným ID.</strong></p>
			<?php else:?>
			<div id="eshophelpdiv" class="postbox" style="width: 90%; padding: 10px 20px 10px 20px;">
			<form action="<?php echo get_option('home');?>/wp-admin/admin.php?page=od-eshop-plugin-edit" method="post" enctype="multipart/form-data">
				<input type="hidden" name="mode" value="<?php echo $mode;?>"/>
				<?php if($mode == 'edit'):?>
				<input type="hidden" name="itemid" value="<?php echo $itemid;?>"/>
				<?php endif;?>
				<table cellspacing="1" cellpadding="1" style="width: 90%;">
					<tr>
						<th scope="row" style="text-align:left; min-width: 120px;"><label for="title-input">Název</label></th>
						<td><input type="text" name="title" id="title-input" value="<?php if($mode == 'edit') echo $item['item_title'];?>" style="width: 100%;"/></td>
					</tr>
					<tr>
						<th scope="row" style="text-align:left; min-width: 120px;"><label for="title_orig-input">Originální název</label></th>
						<td><input type="text" name="title_orig" id="title_orig-input" value="<?php if($mode == 'edit') echo $item['item_title_orig'];?>" style="width: 100%;"/></td>
					</tr>
					<tr>
						<th scope="row" style="text-align:left; min-width: 120px;"><label for="shopno-input">Číslo DVD</label></th>
						<td><input type="text" name="shopno" id="shopno-input" value="<?php if($mode == 'edit') echo $item['item_shopno'];?>"/></td>
					</tr>
					<tr>
						<th scope="row" style="text-align:left; vertical-align:top;"><label for="file_img-input">Obrázek</label></th>
						<td>
							<table style="width:100%;" cellpadding="0" cellspacing="1">
								<tr>
									<td>
										<?php if($mode == 'edit'):?>
										<a href="<?php echo $item['image_url1'];?>"><?php echo str_replace('.jpg', '_original.jpg', $item['item_image']);?></a><br/>
										<a href="<?php echo $item['image_url2'];?>"><?php echo str_replace('.jpg', '_normal.jpg', $item['item_image']);?></a><br/>
										<a href="<?php echo $item['image_url3'];?>"><?php echo str_replace('.jpg', '_small.jpg', $item['item_image']);?></a>
										<?php else:?>
										<p><strong>Zatím není nahrán žádný obrázek.</strong></p>
										<?php endif;?>
										<input type="file" name="file_img" id="file_img-input" value="" style="width: 100%;"/>
									</td>
									<td>
										<!-- XXX Preview of image when mode is 'edit'. -->
										<?php if($mode == 'edit'):?>
										<img src="<?php echo $item['image_url2'];?>" alt="<?php echo $item['item_title'];?>"/>
										<?php else:?>
										<img src="<?php echo $this->get_image_url('noimage_small.gif');?>" alt="Není vybrán žádný obrázek"/>
										<?php endif;?>
									</td>
								</tr>
							</table>
						</td>
					</tr>
					<tr>
						<th scope="row" style="text-align:left; vertical-align:top;"><label>Kategorie</label></th>
						<td><?php echo $this->render_genre_categories_checkboxes('genre_categories', $itemid);?></td>
					</tr>
					<tr>
						<th scope="row" style="text-align:left;"><label for="director-input">Režisér</label></th>
						<td><input type="text" name="director" id="director-input" value="<?php if($mode == 'edit') echo $item['item_director'];?>" style="width: 100%;"/></td>
					</tr>
					<tr>
						<th scope="row" style="text-align:left;"><label for="actor-input">Hlavní herec</label></th>
						<td><input type="text" name="actor" id="actor-input" value="<?php if($mode == 'edit') echo $item['item_actor'];?>" style="width: 100%;"/></td>
					</tr>
					<tr>
						<th scope="row" style="text-align:left;"><label for="language-input">Jazyk</label></th>
						<td><input type="text" name="language" id="language-input" value="<?php if($mode == 'edit') echo $item['item_language'];?>" style="width: 100%;"/></td>
					</tr>
					<tr>
						<th scope="row" style="text-align:left;"><label for="subtitles-input">Titulky</label></th>
						<td><input type="text" name="subtitles" id="subtitles-input" value="<?php if($mode == 'edit') echo $item['item_subtitles'];?>" style="width: 100%;"/></td>
					</tr>
					<tr>
						<th scope="row" style="text-align:left;"><label for="custom-input">Dodatečná položka</label></th>
						<td><input type="text" name="custom" id="custom-input" value="<?php if($mode == 'edit') echo $item['item_custom'];?>" style="width: 100%;"/></td>
					</tr>
					<tr>
						<th scope="row" style="text-align:left;"><label for="prize_category-select">Cenová kategorie</label></th>
						<td><?php echo $this->render_prize_categories_select('prize_category', $item['prize_category_ID']);?></td>
					</tr>
					<tr>
						<td style="text-align: right;"><input type="checkbox" name="display" id="display-input"<?php echo (($item['item_display'] == 1) ? ' checked="checked"' : '');?>/><!-- <?php echo $item['display'];?> --></td>
						<td><label for="display-input">Zobrazit položku na stránkách.</label></td>
					</tr>
				</table>
				<p>
					<input type="submit" value=" Uložit " name="saveediteditem" class="button-primary action" />
				</p>
			</form>
			</div>
			<?php endif;?>
		</div>
<?php 
  }
	
	/**
	 * Renders checkboxes with genre categories
	 * 
   * @param string $aElmName
   * @param integer $aEshopItemId
	 * @return string
	 */
	function render_genre_categories_checkboxes($aElmName = 'genre_categories', $aEshopItemId = null)
	{
		global $wpdb;
		
		$ret = '';
		
		$query = "
			SELECT 
				* , 
				(SELECT COUNT(`genre_category_ID`) FROM `{$wpdb->prefix}eshop_items_to_genre_categories` WHERE `item_ID` = '{$aEshopItemId}' AND `genre_category_ID` = `t1`.`ID`) AS `selected` 
			FROM `{$wpdb->prefix}eshop_genre_categories` AS `t1` 
			WHERE 1 
			ORDER BY `title` ASC ";
		$categories = $wpdb->get_results($query, ARRAY_A);
		
		if(!$categories) {
			return '<p>Zatím nebyly vytvořeny žádné kategorie.</p>';
		}
		
		foreach($categories as $cat) {
			$sel = ($cat['selected'] == '1') ? true : false;
			$ret .= '<input type="checkbox" name="' . $aElmName . '[]" value="' . $cat['ID'] . '" id="' . $aElmName . '-input"' .
					(($sel) ? ' checked="checked"' : '') .
					'/>&nbsp;' . $cat['title'] . '<br/>';
		}
		
		return $ret;
	}
	
  /** 
   * Renders selectbox with prize categories
   *
   * @param string $aElmName
   * @param integer $aSelPrizeCategoryId
   * @return string
   */
	function render_prize_categories_select($aElmName = 'prize_category', $aSelPrizeCategoryId = null)
	{
		global $wpdb;
		
		$ret = '';
		$query = "SELECT * FROM `{$wpdb->prefix}eshop_prize_categories` WHERE 1 ";
		$rows = $wpdb->get_results($query, ARRAY_A);
	
		if(is_null($rows)) {
			return '<p>Zatím nebyly vytvořeny žádné kategorie.</p>';
		}
		
		$ret = '<select name="' . $aElmName . '" id="' . $aElmName . '-select"' .
		    ((!is_null($aSelPrizeCategoryId)) ? ' value="' . $aSelPrizeCategoryId . '"' : '') .
				'>';
		
		foreach($rows as $row) {
			$ret .= '<option value="' . $row['ID'] . '"' .
					(($row['ID'] == $aSelPrizeCategoryId) ? ' selected="selected"' : '') .
					'>' . $row['title'] . ' (' . $row['prize'] . ' Kč)</option>';
		}
		
		$ret .= '</select>';
		
		return $ret;
	}
	
	/**
	 * Renders page for editing genre categories
	 *
	 * @return void
   */
	function genre_categories_page()
	{
		global $wpdb;
		
		$options = $this->get_options();
		
		$op = 'add';
		$cat_id = 0;
		$cat_arr = null;
		
		// Edit/Delete category
		if(isset($_GET['op'])) {
			$op = $_GET['op'];
			$cat_id = isset($_GET['cat_id']) ? $_GET['cat_id'] : null;
			
			if($op == 'edit') {
				$cat_arr = odWpEshopPluginDbModel::getGenreCategory($cat_id);
			} else if($op == 'delete') {
				$query = "DELETE FROM `{$wpdb->prefix}eshop_genre_categories` WHERE `ID` = '{$cat_id}' LIMIT 1 ;";
				$res = $wpdb->query($query);
				
				if($res) {
?>
				<div id="message" class="updated fade">
					<p><strong>Vybraná kategorie byla úspěšně smazána.</strong></p>
				</div>
<?php
				} else {
?>
				<div id="message" class="updated fade">
					<p><strong>Omlouváme se, ale vybraná kategorie byla úspěšně smazána.</strong></p>
				</div>
<?php
				}
				
				$op = 'add';
			}
		}
		
		// Saving edited category/adding new category
		if(isset($_POST['saveditform'])) {
			$op = $_POST['op'];
			$cat_id = $_POST['cat_id'];
			$cat_title = $_POST['title'];
			
			$query = ($op == 'add')
					? "INSERT INTO `{$wpdb->prefix}eshop_genre_categories`
					      ( `ID` , `title` )
					   VALUES
						    ( NULL , '{$cat_title}' );"
					: "UPDATE `{$wpdb->prefix}eshop_genre_categories`
					   SET
								`title` = '{$cat_title}' 
						 WHERE
							  `ID` = '{$cat_id}' LIMIT 1 ;";
								
			$res = $wpdb->query($query);
			
			if($res == 1) {
?>
		<div id="message" class="updated fade">
		  <p><strong>Operace byla úspěšně provedena.</strong></p>
		</div>
<?php
			} else {
?>
		<div id="message" class="error fade">
		  <p><strong>Omlouváme se, ale operace nebyla úspěšně provedena!</strong></p>
		</div>
<?php
			}
			
			$op = 'add';
		}
		
?>
		<div class="wrap">
			<div class="icon32">
				<img src="<?php echo WP_PLUGIN_URL . '/' . self::$plugin_id . '/icon32.png';?>"/>
			</div>
			<h2>Obchod - Kategorie</h2>
			<div style="">
				<div style="width: 45%; float: left; margin-right: 5%;">
					<form action="<?php echo get_option('home');?>/wp-admin/admin.php?page=od-eshop-plugin-genre-categories" 
								method="post" enctype="multipart/form-data">
						<input type="hidden" name="op" value="<?php echo $op;?>"/>
						<input type="hidden" name="cat_id" value="<?php echo $cat_id;?>"/>
						<h3>Přidej/edituj kategorii</h3>
						<table cellspacing="0" style="width:100%;">
							<tr>
								<th style="text-align:left; min-width: 140px;"><label for="title-input">Název</label></th>
								<td><input type="text" name="title" id="title-input" value="<?php if($op == 'edit') { echo $cat_arr['title']; }?>" style="width:100%;"/></td>
							</tr>
							<tr>
							<!--
							</tr>
							<tr>
								<th style="text-align:left;"><label for="parent_category_ID-select">Nadřazená kategorie</label></th>
								<td><?php /*echo $this->render_genre_categories_select('parent_category_ID', 'Vyber nadřazenou kategorii');*/?></td>
							</tr>
							-->
						</table>
						<p style="text-align: right;">
							<input type="submit" name="saveditform" value="Uložit" class="button-primary action"/>
						</p>
					</form>
				</div>
				<div style="width: 50%; float: left; margin: 0px 0px 0px 0px;">
					<form action="<?php echo get_option('home');?>/wp-admin/admin.php?page=od-eshop-plugin-genre-categories-page"
								method="post" enctype="multipart/form-data">
						<div class="tablenav">
							<div class="alignleft actions">
								<select name="action" class="select-action">
									<option value="-1" selected="selected">Vyber akci</option>
									<option value="delete">Smazat</option>
								</select>
								<input type="submit" value="Provést" name="doaction" id="doaction" class="button-secondary action" />
							</div>
							<br class="clear" />
						</div>
						<div class="clear"></div>
						<table  class="widefat post fixed" cellspacing="0">
							<thead>
								<tr>
									<th scope="col" style="width: 5%;"><input type="checkbox" id="downloads-table-selectall-check"/></th>
									<th scope="col" style="width:95%;">Kategorie</th>
								</tr>
							</thead>
							<tfoot>
								<tr>
									<th scope="col" style="width: 5%;"><input type="checkbox" id="downloads-table-selectall-check"/></th>
									<th scope="col" style="width:95%;">Kategorie</th>
								</tr>
							</tfoot>
							<tbody id="the-list" class="list:odeshop">
								<?php echo $this->render_genre_categories_tablerows();?>
							</tbody>
						</table>
						<div class="tablenav">
							<div class="alignleft actions">
								<select name="action" class="select-action">
									<option value="-1" selected="selected">Vyber akci</option>
									<option value="delete">Smazat</option>
								</select>
								<input type="submit" value="Provést" name="doaction" id="doaction" class="button-secondary action" />
							</div>
							<br class="clear" />
						</div>
						<div class="clear"></div>
					</form>
				</div>
				<div class="clear"></div>
			</div>
	  </div>
<?php 
	}
	
  /** 
   * Renders selectbox with genre categories
   *
   * @param string $aElmName
   * @param string $aEmptyItemLabel
   * @param integer $aSelCategory
   * @return string
   */
	function render_genre_categories_select($aElmName = 'genre_category', $aEmptyItemLabel = 'Vyber kategorii', $aSelCategory = null)
	{
		global $wpdb;
		
		$ret = '';
		$query = "SELECT * FROM `{$wpdb->prefix}eshop_genre_categories` WHERE 1 ";
		$rows = $wpdb->get_results($query, ARRAY_A);
	
		if(is_null($rows)) {
			return '';
		}
		
		$ret = '<select name="' . $aElmName . '" id="' . $aElmName . '-select"' .
			    ((!is_null($aSelCategory)) ? ' value="' . $aSelCategory . '"' : ' value="---"') . '>' .
				'<option value="---"' . ((is_null($aSelCategory)) ? ' selected="selected"' : '') . '>' . $aEmptyItemLabel . '</option>';
		
		foreach($rows as $row) {
			$ret .= '<option value="' . $row['ID'] . '"' .
					(($row['ID'] == $aSelCategory) ? ' selected="selected"' : '') .
					'>' . $row['title'] . '</option>';
		}
		
		$ret .= '</select>';
		
		return $ret;
	}
	
	/**
	 * ...
	 * 
	 * @return string
	 */
	function render_genre_categories_tablerows()
	{
		global $wpdb;
		
		$ret = '';
		
		$query = "SELECT * FROM `{$wpdb->prefix}eshop_genre_categories` WHERE 1 ORDER BY `title` ASC ";
		$categories = $wpdb->get_results($query, ARRAY_A);
	
		if(!$categories) {
			return '<tr>' .
						 '<td colspan="2">' .
						 '<p>Zatím nebyly vytvořeny žádné kategorie.</p>' . 
						 '</td>' . 
						 '</tr>';
		}
		
		$sel_categories = (count($sel_categories) > 0) ? $sel_categories : array();
		
		foreach($categories as $cat) {
			$ret .= '<tr>' .
						 '<td style="text-align: right;">' .
						 '<input type="checkbox" name"sel_categories[]" value="' . $cat['ID'] . '"/>' .
						 '</td>' .
						 '<td><p><strong>' . $cat['title'] . '</strong>&nbsp;(' . 
						 '<a href="' . get_option('home') . '/wp-admin/admin.php?page=od-eshop-plugin-genre-categories&amp;cat_id=' . $cat['ID'] . '&amp;op=delete">Smazat</a> | ' .
						 '<a href="' . get_option('home') . '/wp-admin/admin.php?page=od-eshop-plugin-genre-categories&amp;cat_id=' . $cat['ID'] . '&amp;op=edit">Editovat</a>)' .
						 '</p></td>' . 
						 '</tr>';
		}
		
		return $ret;
	}
	
	/**
	 * Returns path to the upload directory.
	 *
	 * @return string
	 */
	function get_uploaddir_path()
	{
		$options = $this->get_options();
		
		return get_bloginfo('home') . '/' . $options['eshop_images_dir'];
	}
	
	/**
	 * Returns URL for the given image.
	 *
	 * @return string
	 */
	function get_image_url($aImage)
	{
		return $this->get_uploaddir_path() . $aImage;
	}
	
	/**
	 * Renders page for editing prize categories
	 *
	 * @return void
   */
	function prize_categories_page()
	{
		$op = 'add';
		$cat_id = 0;
		$cat_arr = null;
		
		// Edit/Delete category
		if(isset($_GET['op'])) {
			$op = $_GET['op'];
			$cat_id = isset($_GET['cat_id']) ? $_GET['cat_id'] : null;
			
			if($op == 'edit') {
				$cat_arr = odWpEshopPluginDbModel::getPrizeCategory($cat_id);
			} else if($op == 'delete') {
			    $res = odWpEshopPluginDbModel::deletePrizeCategory($cat_id);
?>
				<div id="message" class="<?php echo ($res) ? 'updated' : 'error';?> fade">
				    <?php if($res):?>
					<p><strong>Vybraná kategorie byla úspěšně smazána.</strong></p>
					<?php else:?>
					<p><strong>Omlouváme se, ale vybraná kategorie nebyla úspěšně smazána.</strong></p>
					<?php endif;?>
				</div>
<?php
				$op = 'add';
			}
		}
		
		// Saving edited category/adding new category
		if(isset($_POST['saveditform'])) {
			$op = $_POST['op'];
			$cat_id = $_POST['cat_id'];
			$cat_title = $_POST['title'];
			$cat_prize = $_POST['prize'];
			
			$res = ($op == 'add')
			    ? odWpEshopPluginDbModel::addPrizeCategory($cat_title, $cat_prize)
			    : odWpEshopPluginDbModel::updatePrizeCategory($cat_id, $cat_title, $cat_prize);		
?>
            <div id="message" class="<?php echo ($res) ? 'updated' : 'error';?> fade">
                <?php if($res):?>
                <p><strong>Operace byla úspěšně provedena.</strong></p>
                <?php else:?>
                <p><strong>Omlouváme se, ale operace nebyla úspěšně provedena!</strong></p>
                <?php endif;?>
            </div>
<?php	
			$op = 'add';
		}
		
		$categories = odWpEshopPluginDbModel::getPrizeCategories();
?>
		<div class="wrap">
			<div class="icon32">
				<img src="<?php echo WP_PLUGIN_URL . '/' . self::$plugin_id . '/icon32.png';?>"/>
			</div>
			<h2>Obchod - Cenové kategorie</h2>
			<div style="">
				<div style="width: 45%; float: left; margin-right: 5%;">
					<form action="<?php echo get_option('home');?>/wp-admin/admin.php?page=od-eshop-plugin-prize-categories" 
								method="post" enctype="multipart/form-data">
						<input type="hidden" name="op" value="<?php echo $op;?>"/>
						<input type="hidden" name="cat_id" value="<?php echo $cat_id;?>"/>
						<h3>Přidej/edituj kategorii</h3>
						<table cellspacing="0" style="width:100%;">
							<tr>
								<th style="text-align:left; min-width: 140px;"><label for="title-input">Název</label></th>
								<td><input type="text" name="title" id="title-input" value="<?php if($op == 'edit') { echo $cat_arr['title']; }?>" style="width:100%;"/></td>
							</tr>
							<tr>
								<th style="text-align:left; min-width: 140px;"><label for="prize-input">Cena</label></th>
								<td><input type="text" name="prize" id="prize-input" value="<?php if($op == 'edit') { echo $cat_arr['prize']; }?>" style="width:100%;"/></td>
							</tr>
						</table>
						<p style="text-align: right;">
							<input type="submit" name="saveditform" value="Uložit" class="button-primary action"/>
						</p>
					</form>
				</div>
				<div style="width: 50%; float: left; margin: 0px 0px 0px 0px;">
					<form action="<?php echo get_option('home');?>/wp-admin/admin.php?page=od-eshop-plugin-prize-categories"
								method="post" enctype="multipart/form-data">
						<div class="tablenav">
							<div class="alignleft actions">
								<select name="action" class="select-action">
									<option value="-1" selected="selected">Vyber akci</option>
									<option value="delete">Smazat</option>
								</select>
								<input type="submit" value="Provést" name="doaction" id="doaction" class="button-secondary action" />
							</div>
							<br class="clear" />
						</div>
						<div class="clear"></div>
						<table  class="widefat post fixed" cellspacing="0">
							<thead>
								<tr>
									<th scope="col" style="width: 5%;"><input type="checkbox" id="eshop-table-selectall-check"/></th>
									<th scope="col" style="width:95%;">Kategorie</th>
								</tr>
							</thead>
							<tfoot>
								<tr>
									<th scope="col" style="width: 5%;"><input type="checkbox" id="eshop-table-selectall-check"/></th>
									<th scope="col" style="width:95%;">Kategorie</th>
								</tr>
							</tfoot>
							<tbody id="the-list" class="list:odeshop">
							    <?php if(count($categories) > 0):?>
							    <?php foreach($categories as $category):?>
                                <tr>
                                    <td style="text-align: right;">
                                        <input type="checkbox" name="sel_categories[]" value="<?php echo $category['ID'];?>"/>
                                    </td>
                                    <td>
                                        <p>
                                            <strong><?php echo $category['title'];?></strong>&nbsp;
                                            (<a href="<?php echo get_option('home');?>/wp-admin/admin.php?page=od-eshop-plugin-prize-categories&amp;cat_id=<?php echo $category['ID'];?>&amp;op=delete">Smazat</a> | 
                                            <a href="<?php echo get_option('home');?>/wp-admin/admin.php?page=od-eshop-plugin-prize-categories&amp;cat_id=<?php echo $category['ID'];?>&amp;op=edit">Editovat</a>)
                                        </p>
                                    </td>
                                </tr>
							    <?php endforeach;?>
								<?php else:?>
								<tr>
								    <td colspan="2"><p>Zatím nebyly vytvořeny žádné kategorie.</p></td>
								</tr>
								<?php endif;?>
							</tbody>
						</table>
						<div class="tablenav">
							<div class="alignleft actions">
								<select name="action" class="select-action">
									<option value="-1" selected="selected">Vyber akci</option>
									<option value="delete">Smazat</option>
								</select>
								<input type="submit" value="Provést" name="doaction" id="doaction" class="button-secondary action" />
							</div>
							<br class="clear" />
						</div>
						<div class="clear"></div>
					</form>
				</div>
				<div class="clear"></div>
			</div>
	  </div>
<?php 
	}
	
	/**
	 * Renders users page
	 *
	 * @return void
	 */
	function users_page()
	{
		$users = odWpEshopPluginDbModel::getEshopUsers();
		$i = 0;
?>
	<div class="wrap">
		<div class="icon32">
		<img src="<?php echo WP_PLUGIN_URL . '/' . self::$plugin_id . '/icon32.png';?>"/>
		</div>
		<h2>Obchod - Uživatelé</h2>
		<div class="clear"></div>
		<table class="widefat post fixed" cellspacing="0">
		  <thead>
			<tr>
			  <th scope="col" style="width: 5%;" class="manage-column column-cb check-column"><input type="checkbox" /></th>
			  <th scope="col" style="width:25%;" class="manage-column column-cb">Jméno uživatele</th>
			  <th scope="col" style="width:25%;" class="manage-column column-cb">E&ndash;mailová adresa</th>
			  <th scope="col" style="width:20%;" class="manage-column column-cb">Adresa</th>
			  <th scope="col" style="width:10%;" class="manage-column column-cb">Telefon</th>
			  <th scope="col" style="width:15%;" class="manage-column column-cb">Objednávky</th>
			</tr>
		  </thead>
		  <tfoot>
			<tr>
			  <th scope="col" style="width: 5%;" class="manage-column column-cb check-column"><input type="checkbox" /></th>
			  <th scope="col" style="width:25%;" class="manage-column column-cb">Jméno uživatele</th>
			  <th scope="col" style="width:25%;" class="manage-column column-cb">E&ndash;mailová adresa</th>
			  <th scope="col" style="width:20%;" class="manage-column column-cb">Adresa</th>
			  <th scope="col" style="width:10%;" class="manage-column column-cb">Telefon</th>
			  <th scope="col" style="width:15%;" class="manage-column column-cb">Objednávky</th>
			</tr>
		  </tfoot>
		  <tbody id="the-list" class="list:odeshop">
				<?php if(count($users) > 0):?>
				<?php foreach($users as $user):?>
				<tr class="<?php echo (($i++ % 2) ? 'alternate' : '');?> status-inherit\">
					<th scope="row" class="check-column" style="vertical-align: middle;"><input type="checkbox" name="items[]" value="<?php echo $user['item_ID'];?>"/></th>
					<td style="vertical-align: middle;"><strong><?php echo $user['wp_user']->last_name . ', ' . $user['wp_user']->first_name;?></strong></td>
					<td style="vertical-align: middle;"><?php echo $user['wp_user']->user_email;?></td>
					<td style="vertical-align: middle;"><?php echo $user['street'] . '<br />' . $user['town'] . '&nbsp;' . $user['zip'];?></td>
					<td style="vertical-align: middle;"><?php echo $user['phone'];?></td>
					<td style="vertical-align: middle;"><a href="<?php echo get_option('home');?>/wp-admin/admin.php?page=od-eshop-plugin-orders&amp;userid=<?php echo $user['wp_user_id'];?>">Objednávky</a></td>
				</tr>
				<?php endforeach;?>
				<?php else:?>
				<tr>
					<th scope="row" colspan="6">Prozatím nejsou žádní uživatelé vytvořeni.</th>
				</tr>
				<?php endif;?>
		  </tbody>
		</table>
	</div>
<?php 
	}
	
	/**
	 * Renders users page
	 *
	 * @return void
	 */
	function orders_page()
	{
		$options = $this->get_options();
		$order_id = null;
		$user_id = null;
		$current_order = null;
		$order_detail = '';
		$orders = null;
		$i = 0;
		
		// Detail order id
		if(isset($_GET['orderid'])) {
			$order_id = (int) $_GET['orderid'];
			$current_order = odWpEshopPluginDbModel::getOrderById($order_id);
			$order_detail = $this->get_message_for_order($current_order);
		} else {
			// XXX Pridat strankovani
			
			if(!is_null($_GET['userid'])) {
				$user_id = (int) $_GET['userid'];
				$orders = odWpEshopPluginDbModel::getOrdersByUserId($user_id);
			} else {
				$orders = odWpEshopPluginDbModel::getOrders();
			}
		}
?>
	<div class="wrap">
		<div class="icon32">
		<img src="<?php echo WP_PLUGIN_URL . '/' . self::$plugin_id . '/icon32.png';?>"/>
		</div>
		<?php if(is_null($current_order)):?>
		<h2>Obchod - Objednávky</h2>
		<div class="clear"></div>
		<table class="widefat post fixed" cellspacing="0">
		  <thead>
			<tr>
			  <th scope="col" style="width: 5%; vertical-align: middle;" class="manage-column column-cb check-column"><!--<input type="checkbox" />--></th>
			  <th scope="col" style="width:15%; vertical-align: middle;" class="manage-column column-cb">Datum</th>
			  <th scope="col" style="width:20%; vertical-align: middle;" class="manage-column column-cb">Uživatel</th>
			  <th scope="col" style="width:20%; vertical-align: middle;" class="manage-column column-cb">Info o objednávce</th>
			  <th scope="col" style="width:20%; vertical-align: middle;" class="manage-column column-cb">Způsob doručení</th>
			  <th scope="col" style="width:10%; vertical-align: middle;" class="manage-column column-cb">Cena celkem</th>
			  <th scope="col" style="width:10%; vertical-align: middle;" class="manage-column column-cb">Stav</th>
			</tr>
		  </thead>
		  <tfoot>
			<tr>
			  <th scope="col" style="width: 5%; vertical-align: middle;" class="manage-column column-cb check-column"><!--<input type="checkbox" />--></th>
			  <th scope="col" style="width:15%; vertical-align: middle;" class="manage-column column-cb">Datum</th>
			  <th scope="col" style="width:20%; vertical-align: middle;" class="manage-column column-cb">Uživatel</th>
			  <th scope="col" style="width:20%; vertical-align: middle;" class="manage-column column-cb">Info o objednávce</th>
			  <th scope="col" style="width:20%; vertical-align: middle;" class="manage-column column-cb">Způsob doručení</th>
			  <th scope="col" style="width:10%; vertical-align: middle;" class="manage-column column-cb">Cena celkem</th>
			  <th scope="col" style="width:10%; vertical-align: middle;" class="manage-column column-cb">Stav</th>
			</tr>
		  </tfoot>
		  <tbody id="the-list" class="list:odeshop">
		    <?php if(count($orders) > 0):?>
				<?php foreach($orders as $order):?>
		    <tr class="<?php echo (($i++ % 2) ? 'alternate' : '' ) ;?> status-inherit">
				<th scope="row" class="check-column" style="vertical-align: middle;"><!--<input type="checkbox" name="items[]" value="<?php echo $order['order_ID'];?>"/>--><code><?php echo $order['order_ID'];?></code></th>
				<td style="vertical-align: middle;"><code><?php echo $order['order_finished_when'];?></code></td>
				<td style="vertical-align: middle;"><strong><?php echo $order['order_wpuser']->last_name . ', ' . $order['order_wpuser']->first_name;?></strong></td>
				<td style="vertical-align: middle;">
				    Počet položek: <strong><?php echo $order['order_items_count'];?></strong><br/>
				    Cena celkem: <strong><?php echo $order['order_total_prize'];?></strong> Kč<br/>
						<a href="<?php echo get_option('home');?>/wp-admin/admin.php?page=od-eshop-plugin-orders&amp;orderid=<?php echo $order['order_ID'];?>">Detail objednávky</a>
				</td>
				<td style="vertical-align: middle;"><?php echo ($order['order_delivery'] == 'postoffice') ? 'Česká pošta, 99 Kč' : 'osobně';?></td>
				<td style="vertical-align: middle;"><?php echo $order['order_total_prize_with_delivery'];?> Kč</td>
				<td style="vertical-align: middle;"><?php echo $order['order_status_label'];?></td>
		    </tr>
				<?php endforeach;?>
				<?php else:?>
				<tr>
					<?php if(is_null($user_id)):?>
					<th scope="row" colspan="6">Prozatím nejsou žádné objednávky vytvořeny.</th>
					<?php else:?>
					<th scope="row" colspan="6">Tento uživatel zatím neodeslal žádné objednávky. Zobrazit <a href="<?php echo get_option('home');?>/wp-admin/admin.php?page=od-eshop-plugin-orders">všechny objednávky</a>.</th>
					<?php endif;?>
				</tr>
				<?php endif;?>
		  </tbody>
		</table>
		<?php else:?>
		<h2>Obchod - Detail objednávky č. <code><?php echo $current_order->order_ID;?></code></h2>
		<pre><?php echo $order_detail;?></pre>
		<hr/>
		<p>
			<a href="<?php echo get_option('home');?>/wp-admin/admin.php?page=od-eshop-plugin-orders">Zpět na přehled objednávek</a>
		</p>
		<?php endif;?>
	</div>
<?php 
	}
	
	/**
	 * Renders eshop statistics
	 *
	 * @return void
	 */
	function stats_page()
	{
	    $options = $this->get_options();
	    $last_render_time = $options['eshop_stats_last_render_time'];
	    // XXX Cache rendered images!
	    //$rerender = false;
	    
	    // Statistiky dle celkovych prodeju a kategorii za poslednich 10 mesicu
	    if(isset($_POST['graph_filter'])) {
	        $sel_months = (isset($_POST['months'])) ? (int) $_POST['months'] : 10;
	        $sel_start_month = (isset($_POST['start_month'])) ? (int) $_POST['start_month'] : date('m');
	        $sel_start_year = (isset($_POST['start_year'])) ? (int) $_POST['start_year'] : date('Y');
	        $show_total_count = (isset($_POST['show_total'])) ? true : false;
	    } else {
	        $sel_months = 10;
	        $sel_start_month = date('m');
	        $sel_start_year = date('Y');
	        $show_total_count = true;
	    }
	    
	    $data1 = odWpEshopPluginStats::getStats_sellsInMonths($sel_months, $sel_start_month, $sel_start_year, $show_total_count);
	    $imgurl1 = odWpEshopPluginStats::renderStats_sellsInMonths($data1);
	    
	    // Pomer celkovych prodeju dle cenovych kategorii kategorii za celkovy cas (kolac)
	    $data2 = odWpEshopPluginStats::getStats_sellsByPrizeCategories();
	    $imgurl2 = odWpEshopPluginStats::renderStats_sellsByPrizeCategories($data2, '_prize');
	    // XXX Tady by mel byt taky pocet prodeju dle jednotlivych cenovych kategorii za celkovy cas, 
	    //     protoze to neni moc pouzitelne toto...
	    $data3 = odWpEshopPluginStats::getStats_sellsByPrizeCategories(true);
	    $imgurl3 = odWpEshopPluginStats::renderStats_sellsByPrizeCategories($data3, '_count', false);
	    
	    // Pomer celkovych prodeju dle zanru za celkovy cas (kolac)
	    $data4 = odWpEshopPluginStats::getStats_sellsByGenres(false, true);
	    $imgurl4 = odWpEshopPluginStats::renderStats_sellsByGenres($data4, '_prize');
	    // XXX Pomer poctu prodeju dle zanru za celkovy cas (kolac)
	    $data5 = odWpEshopPluginStats::getStats_sellsByGenres(true, true);
	    $imgurl5 = odWpEshopPluginStats::renderStats_sellsByGenres($data5, '_count', false);
?>
	<div class="wrap">
		<div class="icon32">
		<img src="<?php echo WP_PLUGIN_URL . '/' . self::$plugin_id . '/icon32.png';?>"/>
		</div>
		<h2>Obchod - Statistiky (grafické)</h2>
		<div class="clear"></div>
		<table cellspacing="0" style="width: 98%;">
			<tbody>
			    <!-- Hlavni graf prodeju -->
				<tr>
					<td colspan="2" style="text-align: center;">
					    <p><strong>Prodeje dle cenových kategorií</strong><br/>
					    <span style="font-size: 90%;">Detailní statistiky prodejů za 10 posledních měsíců s rozlišením jednotlivých cenových kategorií.</span></p>
					    <img src="<?php echo $imgurl1;?>" alt="Graf - Prodeje dle cenových kategorií" title="Graf - Prodeje dle cenových kategorií"/>
					    <form action="#" method="post" style="width: 738px; margin:0px auto 0px auto;background-color: #f2f2f2; border: 1px solid #ccc;">
					        <table cellspacing="1" cellpadding="1" style="width: 100%;">
					            <tr>
					                <td style="text-align: center; vertical-align: middle;">
					                    <span style="font-size: 85%;">Počet měsíců</span>
					                    <select name="months" style="width: 45px;">
					                        <option value="12"<?php if($sel_months == 12) echo ' selected="selected"';?>>12</option>
					                        <option value="10"<?php if($sel_months == 10) echo ' selected="selected"';?>>10</option>
					                        <option value="6"<?php if($sel_months == 6) echo ' selected="selected"';?>>6</option>
					                    </select><span style="font-size: 85%;">, </span>
					                    <span style="font-size: 85%;">počáteční měsícem</span>
					                    <select name="start_month" style="width: 45px;">
					                        <option value="1"<?php if($sel_start_month == 1) echo ' selected="selected"';?>> 1</option>
					                        <option value="2"<?php if($sel_start_month == 2) echo ' selected="selected"';?>> 2</option>
					                        <option value="3"<?php if($sel_start_month == 3) echo ' selected="selected"';?>> 3</option>
					                        <option value="4"<?php if($sel_start_month == 4) echo ' selected="selected"';?>> 4</option>
					                        <option value="5"<?php if($sel_start_month == 5) echo ' selected="selected"';?>> 5</option>
					                        <option value="6"<?php if($sel_start_month == 6) echo ' selected="selected"';?>> 6</option>
					                        <option value="7"<?php if($sel_start_month == 7) echo ' selected="selected"';?>> 7</option>
					                        <option value="8"<?php if($sel_start_month == 8) echo ' selected="selected"';?>> 8</option>
					                        <option value="9"<?php if($sel_start_month == 9) echo ' selected="selected"';?>> 9</option>
					                        <option value="10"<?php if($sel_start_month == 10) echo ' selected="selected"';?>>10</option>
					                        <option value="11"<?php if($sel_start_month == 11) echo ' selected="selected"';?>>11</option>
					                        <option value="12"<?php if($sel_start_month == 12) echo ' selected="selected"';?>>12</option>
					                    </select>
					                    <span style="font-size: 85%;">a rokem</span>
					                    <select name="start_year" style="width: 60px;">
					                        <?php for($i = 0; $i < 10; $i++):?>
					                        <option value="<?php echo ($sel_start_year - $i);?>"<?php if(($sel_start_year - $i) == $sel_start_year) echo ' selected="selected"';?>><?php echo ($sel_start_year - $i);?></option>
					                        <?php endfor;?>
					                    </select>
					                    <span style="font-size: 85%;">(Zobrazit celkové prodeje?</span>
					                    <input type="checkbox" name="show_total" checked="checked"/>
					                    <span>)</span>
					                   <input type="submit" name="graph_filter" value="Potvrdit" class="button-primary action"/>
					                </td>
					            </tr>
					        </table>
					    </form>
					</td>
			    </tr>
			    <!-- Kolace pro prodeje dle cenovych kategorii
			    <tr><td colspan="2" style="width: 50%; text-align: center; padding-top: 15px;"><strong>Prodeje dle cenových kategorií</strong></td></tr>
			    <tr>
			        <td style="width: 40%; text-align: center;font-size: 90%;">V Kč</td>
			        <td style="width: 60%; text-align: center;font-size: 90%;">V ks</td>
			    </tr>
				<tr>
					<td style="width: 40%; text-align: center; border: 2px solid #f30;">
					    <img src="<?php echo $imgurl2;?>" alt="Graf - Celkové prodeje dle cenových kategorií" title="Graf - Celkové prodeje dle cenových kategorií"/></td>
					<td style="width: 60%; text-align: center; border: 2px solid #f30;">
					    <img src="<?php echo $imgurl3;?>" alt="Graf - Počty prodejů dle cenových kategorií" title="Graf - Počty prodejů dle cenových kategorií"/></td>
			    </tr> -->
			    <!-- Kolace pro prodeje dle zanrovych kategorii -->
			    <tr><td colspan="2" style="width: 50%; text-align: center; padding-top: 15px;"><strong>Prodeje dle žánrů</strong></td></tr>
			    <tr>
			        <td style="width: 40%; text-align: center;font-size: 90%;">V Kč</td>
			        <td style="width: 60%; text-align: center;font-size: 90%;">V ks</td>
			    </tr>
				<tr>
					<td style="width: 40%; text-align: center;">
					    <img src="<?php echo $imgurl4;?>" alt="Graf - Celkové prodeje dle žánrů" title="Graf - Celkové prodeje dle žánrů"/></td>
					<td style="width: 60%; text-align: center;">
					    <img src="<?php echo $imgurl5;?>" alt="Graf - Počty prodejů dle žánrů" title="Graf - Počty prodejů dle žánrů"/></td>
			    </tr>
			</tbody>
	    </table>
	</div>
<?php
	}
	
	/**
	 * Renders eshop statistics
	 *
	 * @return void
	 */
	function stats_page_text()
	{
	    $options = $this->get_options();
	    
	    // Statistiky dle celkovych prodeju a kategorii za poslednich 10 mesicu
	    if(isset($_POST['stats_filter'])) {
	        $sel_month = (isset($_POST['month'])) ? (int) $_POST['month'] : date('m');
	        $sel_year = (isset($_POST['year'])) ? (int) $_POST['year'] : date('Y');
	    } else {
	        $sel_month = date('m');
	        $sel_year = date('Y');
	    }
	    $data = odWpEshopPluginStats::getStats_sellsInMonth($sel_month, $sel_year);
?>
	<div class="wrap">
		<div class="icon32">
		<img src="<?php echo WP_PLUGIN_URL . '/' . self::$plugin_id . '/icon32.png';?>"/>
		</div>
		<?php if(!isset($_GET['pg'])):?>
		<h2>Obchod - Statistiky (textové)</h2>
		<div class="clear"></div>
        <table style="width: 80%;">
            <tr>
                <th colspan="3">Statistiky prodejů za zvolené období: <?php echo $data['year'] . '-' . $data['month'];?></th>
            </tr>
            <?php foreach($data['sells'] as $sells_cat => $sells):?>
            <tr>
                <th scope="row" style="width: 30%; text-align: left;">DVD za <strong><?php echo $sells_cat;?></strong></th>
                <td style="width: 25%; text-align: right;"><strong><?php echo $sells['total_count'];?></strong> Ks</td>
                <td style="width: 25%; text-align: right;"><strong><?php echo $sells['total_prize'];?></strong> Kč</td>
            </tr>
            <?php endforeach;?>
            <tr>
                <td colspan="3" style="text-align: center; vertical-align: middle;">
				    <form action="#" method="post" style="background-color: #f2f2f2; border: 1px solid #ccc;">
	                    <span style="font-size: 85%;">Statistiky za měsíc</span> 
	                    <select name="month" style="width: 80px;">
	                        <option value="1"<?php if($sel_month == 1) echo ' selected="selected"';?>>leden</option>
	                        <option value="2"<?php if($sel_month == 2) echo ' selected="selected"';?>>únor</option>
	                        <option value="3"<?php if($sel_month == 3) echo ' selected="selected"';?>>březen</option>
	                        <option value="4"<?php if($sel_month == 4) echo ' selected="selected"';?>>duben</option>
	                        <option value="5"<?php if($sel_month == 5) echo ' selected="selected"';?>>květen</option>
	                        <option value="6"<?php if($sel_month == 6) echo ' selected="selected"';?>>červen</option>
	                        <option value="7"<?php if($sel_month == 7) echo ' selected="selected"';?>>červenec</option>
	                        <option value="8"<?php if($sel_month == 8) echo ' selected="selected"';?>>srpen</option>
	                        <option value="9"<?php if($sel_month == 9) echo ' selected="selected"';?>>září</option>
	                        <option value="10"<?php if($sel_month == 10) echo ' selected="selected"';?>>říjen</option>
	                        <option value="11"<?php if($sel_month == 11) echo ' selected="selected"';?>>listopad</option>
	                        <option value="12"<?php if($sel_month == 12) echo ' selected="selected"';?>>prosinec</option>
	                    </select>
	                    <span style="font-size: 85%;">roku</span>
	                    <select name="year" style="width: 60px;">
	                        <?php for($i = 0; $i < 10; $i++):?>
	                        <option value="<?php echo ($sel_year - $i);?>"<?php if(($sel_year - $i) == $sel_year) echo ' selected="selected"';?>><?php echo ($sel_year - $i);?></option>
	                        <?php endfor;?>
	                    </select>
	                    <input type="submit" name="stats_filter" value="Potvrdit" class="button-primary action"/>
	                 </form>
                </td>
            </tr>
        </table>
		<p class="clear"> &nbsp;</p>
		<table cellspacing="0" style="width:100%;">
			<tbody>
				<tr>
					<th scope="col" style="width: 50%; vertical-align: middle;" class="manage-column column-cb">10 nejprodávanějších DVD</th>
					<th scope="col" style="width: 50%; vertical-align: middle;" class="manage-column column-cb">10 nejaktivnějších uživatelů</th>
				</tr>
				<tr>
					<td style="border-right: 1px solid #ccc;">
						<ol>
							<?php foreach(odWpEshopPluginDbModel::getStatsByEshopItems(10) as $eshop_item):?>
							<li>
								<a href="<?php echo get_option('home');?>/wp-admin/admin.php?page=od-eshop-plugin-edit&amp;itemid=<?php echo $eshop_item['item_ID'];?>"><?php echo $eshop_item['item_title'];?></a> -
								prodáno <strong><?php echo $eshop_item['item_sellcount'];?></strong> ks,
								celkem za <strong><?php echo $eshop_item['item_sell'];?></strong> Kč.
							</li>
							<?php endforeach;?>
						</ol>
					</td>
					<td>
						<ol>
							<?php foreach(odWpEshopPluginDbModel::getStatsByEshopUsers(10) as $userId => $userArr):?>
							<li>
								<strong><?php echo $userArr['user_fullname'];?></strong> -
								objednávek <strong><?php echo $userArr['orders_count'];?></strong>,
								celkem za <strong><?php echo $userArr['orders_prize'];?></strong> Kč.
							</li>
							<?php endforeach;?>
						</ol>
					</td>	
				</tr>
				<tr>
					<th style="font-weight: normal; width: 50%; vertical-align: middle;"><a href="<?php echo get_option('home');?>/wp-admin/admin.php?page=od-eshop-plugin-stats-text&amp;pg=items-stats">Přehled prodejů všech DVD</a></th>
					<th style="font-weight: normal; width: 50%; vertical-align: middle;"><a href="<?php echo get_option('home');?>/wp-admin/admin.php?page=od-eshop-plugin-stats-text&amp;pg=users-stats">Přehled uživatelů</a></th>
				</tr>
			</tbody>
		</table>
		<?php elseif($_GET['pg'] == 'items-stats'):?>
		<h2>Obchod - Statistiky dle DVD</h2>
		<div class="clear"></div>
		<p>V následující tabulce je přehled prodejů DVD,které se prodaly alespoň jednou. Zpět na <a href="<?php echo get_option('home');?>/wp-admin/admin.php?page=od-eshop-plugin-stats-text">přehled statistik</a>.</p>
		<table class="widefat post fixed" cellspacing="0">
		  <thead>
				<tr>
					<th scope="col" style="width: 60%; vertical-align: middle;" class="manage-column column-cb">DVD</th>
					<th scope="col" style="width: 20%; vertical-align: middle;" class="manage-column column-cb">Prodáno kusů</th>
					<th scope="col" style="width: 20%; vertical-align: middle;" class="manage-column column-cb">Celková cena</th>
				</tr>
		  </thead>
		  <tfoot>
				<tr>
					<th scope="col" style="width: 50%; vertical-align: middle;" class="manage-column column-cb">DVD</th>
					<th scope="col" style="width: 20%; vertical-align: middle;" class="manage-column column-cb">Prodáno kusů</th>
					<th scope="col" style="width: 20%; vertical-align: middle;" class="manage-column column-cb">Celková cena</th>
				</tr>
		  </tfoot>
			<tbody>
				<?php foreach(odWpEshopPluginDbModel::getStatsByEshopItems(1000) as $eshop_item):?>
				<tr>
					<th scope="row">
						<a href="<?php echo get_option('home');?>/wp-admin/admin.php?page=od-eshop-plugin-edit&amp;itemid=<?php echo $eshop_item['item_ID'];?>"><?php echo $eshop_item['item_title'];?></a>
					</th>
					<td><?php echo $eshop_item['item_sellcount'];?></td>
					<td><strong><?php echo $eshop_item['item_sell'];?></strong> Kč</td>
				</tr>
				<?php endforeach;?>
			</tbody>
		</table>
		<?php elseif($_GET['pg'] == 'users-stats'):?>
		<h2>Obchod - Statistiky dle uživatelů</h2>
		<div class="clear"></div>
		<p>Zpět na <a href="<?php echo get_option('home');?>/wp-admin/admin.php?page=od-eshop-plugin-stats-text">přehled statistik</a>.<!-- Celkem uživatelů: <strong>0</strong>.--></p>
		<table class="widefat post fixed" cellspacing="0">
		  <thead>
				<tr>
					<th scope="col" style="width: 33%; vertical-align: middle;" class="manage-column column-cb">Uživatel</th>
					<th scope="col" style="width: 33%; vertical-align: middle;" class="manage-column column-cb">Počet objednávek</th>
					<th scope="col" style="width: 33%; vertical-align: middle;" class="manage-column column-cb">Celková cena objednávek</th>
				</tr>
		  </thead>
		  <tfoot>
				<tr>
					<th scope="col" style="width: 33%; vertical-align: middle;" class="manage-column column-cb">Uživatel</th>
					<th scope="col" style="width: 33%; vertical-align: middle;" class="manage-column column-cb">Počet objednávek</th>
					<th scope="col" style="width: 33%; vertical-align: middle;" class="manage-column column-cb">Celková cena objednávek</th>
				</tr>
		  </tfoot>
			<tbody>
				<?php foreach(odWpEshopPluginDbModel::getStatsByEshopUsers(1000) as $userId => $userArr):?>
				<tr>
					<th scope="row"><?php echo $userArr['user_fullname'];?></th>
					<td><?php echo $userArr['orders_count'];?></td>
					<td><strong><?php echo $userArr['orders_prize'];?></strong> Kč</td>
				</tr>
				<?php endforeach;?>
			</tbody>
		</table>
		<?php endif;?>
	</div>
<?php
	}
	
	/**
	 * Renders page for FAQ
	 *
	 * @return void
	 */
	function faq_page()
	{
		global $wpdb;
		
		$options = $this->get_options();
?>
		<div class="wrap">
			<div class="icon32">
			<img src="<?php echo WP_PLUGIN_URL . '/' . self::$plugin_id . '/icon32.png';?>"/>
			</div>
			<h2>Obchod - Dotazy</h2>
<?php
		if((isset($_POST['doaction']) || isset($_POST['doaction2']))) {
			$action = ($_POST['action'] != '-1') ? $_POST['action'] : $_POST['action2'];
			$items = (isset($_POST['items'])) ? $_POST['items'] : array();
			
			if(count($items) == 0) {
?>
			<div id="message" class="error fade"><p><strong>Nebyly označeny žádné položky.</strong></p></div>
<?php
			} else if($action == '-1' || $action == '-2') {
?>
				<div id="message" class="error fade"><p><strong>Nebyly označeny žádné položky.</strong>.</p></div>
<?php
			} else { // Possible actions: 'delete'
				$query = "DELETE FROM `{$wpdb->prefix}eshop_faq` WHERE ";
				
				for($i=0; $i<count($items); $i++) {
					$query = $query . "`ID`='" . $items[$i] . "' " . ((($i+1)==count($items)) ? '' : 'OR ');
				}
				
				$res = $wpdb->query($query);
				
				if(!$res) {
					if($action == 'delete') {
?>
			  <div id="message" class="error fade"><p>Vyskytla se chyba. Položky nebyly smazány.</p></div>
<?php
					} else { 
?>
			  <div id="message" class="error fade"><p>Vyskytla se chyba. Položky nebyly aktualizovány.</p></div>
<?php
					}
				} else {
?>
			  <div id="message" class="updated fade"><p>Smazáno položek: <strong><?php echo $res;?></strong>.</p></div>
<?php
				}
			}
		}
?>
	  <form action="<?php echo get_option('home');?>/wp-admin/admin.php?page=od-eshop-plugin-faq" method="post" enctype="multipart/form-data">
		<div class="tablenav">
		  <div class="alignleft actions">
			<select name="action" class="select-action">
			    <option value="-1" selected="selected">Vyber akci</option>
    			<option value="delete">Smazat</option>
			</select>
			<input type="submit" value="Provést" name="doaction" id="doaction" class="button-secondary action" />
		  </div>
		  <br class="clear" />
		</div>
		<div class="clear"></div>
		<table class="widefat post fixed" cellspacing="0">
		  <thead>
			<tr>
			  <th scope="col" style="width: 5%;" class="manage-column column-cb check-column"><input type="checkbox" /></th>
			  <th scope="col" style="width:10%;" class="manage-column column-cb">Datum</th>
			  <th scope="col" style="width:35%;" class="manage-column column-cb">Odesílatel</th>
			  <th scope="col" style="width:50%;" class="manage-column column-cb">Text</th>
			</tr>
		  </thead>
		  <tfoot>
			<tr>
			  <th scope="col" style="width: 5%;" class="manage-column column-cb check-column"><input type="checkbox" /></th>
			  <th scope="col" style="width:10%;" class="manage-column column-cb">Datum</th>
			  <th scope="col" style="width:35%;" class="manage-column column-cb">Odesílatel</th>
			  <th scope="col" style="width:50%;" class="manage-column column-cb">Text</th>
			</tr>
		  </tfoot>
		  <tbody id="the-list" class="list:odeshop">
			<?php echo $this->_render_faq_list();?>
		  </tbody>
		</table>
		<div class="tablenav">
		  <div class="alignleft actions">
				<select name="action2" class="select-action">
			        <option value="-1" selected="selected">Vyber akci</option>
        			<option value="delete">Smazat</option>
				</select>
				<input type="submit" value="Provést" name="doaction2" id="doaction2" class="button-secondary action" />
		  </div>
		  <br class="clear" />
		</div>
	  </form>
	</div>
<?php 
	}
	
	/**
	 * ...
	 *
	 * @return string
	 */
	function _render_faq_list()
	{
	    global $wpdb;
		
		$ret = "";
		$rows = $wpdb->get_results("
				SELECT * 
				FROM `{$wpdb->prefix}eshop_faq` 
				WHERE 1  
				ORDER BY `created` ASC ", ARRAY_A);
		$i = 0;
		
		if(is_null($rows)) {
			return "";
		}
		
		foreach($rows as $row) {
		    $created = $row['created'];
			$sender = '<strong>' . $row['sender_name'] . '</strong><br/>' . 
			          '<a href="mailto:' . $row['sender_mail'] . '">' . $row['sender_mail']. '</a><br/>' . 
			          $row['sender_phone'];
		    $question = $row['question'];
		    
			$ret .= "
					<tr class=\"".(($i++%2)?'alternate':'')."status-inherit\">
						<th scope=\"row\" class=\"check-column\" style=\"vertical-align: middle;\"><input type=\"checkbox\" name=\"items[]\" value=\"".$row['ID']."\"/></td>
						<td style=\"vertical-align: middle;\">{$created}</td>
						<td style=\"vertical-align: middle;\">{$sender}</td>
						<td style=\"vertical-align: middle;\">{$question}</td>
					</tr>";
			$i++;
		}
		
		return $ret;
	}
  
  /** 
   * Renders settings page for the plugin 
   * 
   * @return void
   */
  function settings_page()
  {
		$options = $this->get_options();
?>
		<div class="wrap">
			<div class="icon32">
				<img src="<?php echo WP_PLUGIN_URL . '/' . self::$plugin_id . '/icon32.png';?>"/>
			</div>
			<h2>Obchod - Nastavení</h2>
<?php
		if(isset($_POST['settings_save'])){
			// Images settings
			$options['eshop_images_dir'] = $_POST['option-eshop_images_dir'];
			$options['noimage_name'] = (int) $_POST['option-noimage_name'];
			
			// Eshop pages settings
			$options['eshop_homepage_id'] = (int) $_POST['option-eshop_homepage_id'];
			$options['eshop_main_page_id'] = (int) $_POST['option-eshop_main_page_id'];
			$options['eshop_main_page_text_id'] = (int) $_POST['option-eshop_main_page_text_id'];
			$options['eshop_detail_page_id'] = (int) $_POST['option-eshop_detail_page_id'];
			$options['eshop_basket_page_id'] = (int) $_POST['option-eshop_basket_page_id'];
			$options['eshop_search_results_page_id'] = (int) $_POST['option-eshop_search_results_page_id'];
			$options['eshop_user_registration_page_id'] = (int) $_POST['option-eshop_user_registration_page_id'];
			$options['eshop_user_login_page_id'] = (int) $_POST['option-eshop_user_login_page_id'];
			$options['eshop_contact_form_page_id'] = (int) $_POST['option-eshop_contact_form_page_id'];
			
			// Eshop users settings
			
			// Set up WordPress's option `default_role` for `customer`  
			if(isset($_POST['correct_default_role'])) {
				update_option('default_role', 'customer');
			}
			
			// TODO If user entered URL check if is valid!
			if($_POST['option-after_login_redirect'] == 'otherpage') {
				$options['after_login_redirect'] = $_POST['other_loginredirect_page'];
			} else {
				$options['after_login_redirect'] = $_POST['option-after_login_redirect'];
			}
			
			// TODO Enable simple user admin
			/*if(isset($_POST['option-enable_simple_user_admin'])) {
				$options['enable_simple_user_admin'] = true;
			} else {
				$options['enable_simple_user_admin'] = false;
			}*/
			
			// Custom stylesheet fo WordPress login page
			if(isset($_POST['use_custom_login_stylesheet'])) {
				$options['use_custom_login_stylesheet'] = true;
				$options['custom_login_stylesheet'] = $_POST['option-custom_login_stylesheet'];
			}
			
			update_option(self::$plugin_id . '-options', $options);
?>
			<div id="message" class="updated fade">
				<p>Nastavení aktualizováno.</p>
			</div>
<?php
		}
		
		$current_user = wp_get_current_user();
		$is_admin = ($current_user->has_cap('administrator'));
		$used_redirect = $options['after_login_redirect'];
?>
			<form action="<?php echo get_option('home');?>/wp-admin/admin.php?page=od-eshop-plugin-settings" method="post" enctype="multipart/form-data">
				<div>
					<table class="widefat post fixed" cellpadding="1" cellspacing="1" style="width:100%;">
						<tr>
							<td colspan="2" style="background-color:#ccc;"><h3>Obrázky</h3></td>
						</tr>
						<tr>
							<th scope="row"><label for="option-eshop_images_dir">Adresář pro obrázky:</label></th>
							<td><input type="text" name="option-eshop_images_dir" style="min-width: 300px;" value="<?php echo $options['eshop_images_dir'];?>"/></td>
						</tr>
						<tr>
							<th scope="row"><label for="option-noimage_name">Obrázek pro položky, kterým chybí vlastní:</label></th>
							<td><input type="text" name="option-noimage_name" style="min-width: 300px;" value="<?php echo $options['noimage_name'];?>"/></td>
						</tr>
						<tr>
							<td colspan="2" style="background-color:#ccc;"><h3>Stránky obchodu</h3></td>
						</tr>
						<tr>
							<th scope="row"<?php if($is_admin) echo ' style="border-bottom: 0px none;"';?>>
								<label for="option-eshop_homepage_id">Vložte ID domovské stránky webových stránek:</label>
							</th>
							<td<?php if($is_admin) echo ' style="border-bottom: 0px none;"';?>>
								<input type="text" name="option-eshop_homepage_id" value="<?php echo $options['eshop_homepage_id'];?>" style="width: 80px;"/> 
							</td>
						</tr>
						<tr>
							<td colspan="2">
								<?php if($is_admin):?>Aby jste mohli používat dané nastavení, musíte upravit soubor <code>index.php</code> vašeho tématu vzhledu (<a href="#">více informací</a>).<?php endif;?>
							</td>
						</tr>
						<tr>
							<th scope="row"><label for="option-eshop_main_page_id">Vložte ID hlavní stránky obchodu:</label></th>
							<td>
								<input type="text" name="option-eshop_main_page_id" value="<?php echo $options['eshop_main_page_id'];?>" style="width: 80px;"/>
								<?php if($is_admin):?>&nbsp;Kód:&nbsp;<code>[eshop_main_page]</code><?php endif;?>
							</td>
						</tr>
						<tr>
							<th scope="row"><label for="eshop_main_page_text_id"></label>ID stránky, která obsahuje text pro stránku s přehledem kategorií eshopu (volitelné):</th>
							<td style="vertical-align: middle;">
								<input type="text" name="option-eshop_main_page_text_id" value="<?php echo $options['eshop_main_page_text_id'];?>" style="width: 80px;"/>
							</td>
						</tr>
						<tr>
							<th scope="row"><label for="option-eshop_detail_page_id">Vložte ID stránky s detailem výrobku:</label></th>
							<td>
								<input type="text" name="option-eshop_detail_page_id" value="<?php echo $options['eshop_detail_page_id'];?>" style="width: 80px;"/>
								<?php if($is_admin):?>&nbsp;Kód:&nbsp;<code>[eshop_detail_page]</code><?php endif;?>
							</td>
						</tr>
						<tr>
							<th scope="row"><label for="option-eshop_basket_page_id">Vložte ID stránky pro stránku s nákupním košíkem:</label></th>
							<td>
								<input type="text" name="option-eshop_basket_page_id" value="<?php echo $options['eshop_basket_page_id'];?>" style="width: 80px;"/>
								<?php if($is_admin):?>&nbsp;Kód:&nbsp;<code>[eshop_basket_page]</code><?php endif;?>
							</td>
						</tr>
						<tr>
							<th scope="row"><label for="option-eshop_search_results_page_id">Vložte ID stránky s výsledky vyhledávání:</label></th>
							<td>
								<input type="text" name="option-eshop_search_results_page_id" value="<?php echo $options['eshop_search_results_page_id'];?>" style="width: 80px;"/>
								<?php if($is_admin):?>&nbsp;Kód:&nbsp;<code>[eshop_search_results_page]</code><?php endif;?>
							</td>
						</tr>
						<tr>
							<th scope="row"><label for="option-eshop_user_registration_page_id">Vložte ID stránky pro registraci uživatele:</label></th>
							<td>
								<input type="text" name="option-eshop_user_registration_page_id" value="<?php echo $options['eshop_user_registration_page_id'];?>" style="width: 80px;"/>
								<?php if($is_admin):?>&nbsp;Kód:&nbsp;<code>[eshop_user_registration_page]</code><?php endif;?>
							</td>
						</tr>
						<tr>
							<th scope="row"><label for="option-eshop_user_login_page_id">Vložte ID stránky pro přihlášení uživatele:</label></th>
							<td>
								<input type="text" name="option-eshop_user_login_page_id" value="<?php echo $options['eshop_user_login_page_id'];?>" style="width: 80px;"/>
								<?php if($is_admin):?>&nbsp;Kód:&nbsp;<code>[eshop_user_login_page]</code><?php endif;?>
							</td>
						</tr>
						<tr>
							<th scope="row"><label for="option-eshop_contact_form_page_id">Vložte ID stránky pro kontantní formulář:</label></th>
							<td>
								<input type="text" name="option-eshop_contact_form_page_id" value="<?php echo $options['eshop_contact_form_page_id'];?>" style="width: 80px;"/>
								<?php if($is_admin):?>&nbsp;Kód:&nbsp;<code>[eshop_contact_form_page]</code><?php endif;?>
							</td>
						</tr>
						<tr>
							<td colspan="2" style="background-color:#ccc;"><h3>Uživatelé</h3></td>
						</tr>
						<?php if(get_option('default_role') != 'customer'):?>
						<tr>
							<td colspan="2">
								<input type="checkbox" name="correct_default_role"/>&nbsp;
								Zvolit roli <em>Zákazník</em> jako výchozí pro nově zaregistrované uživatele (<strong>doporučeno!</strong>)
							</td>
						</tr>
						<?php endif;?>
						<tr>
							<td colspan="2">
								Defaultní přesměrování po úspěšném přihlášením vede na:<br/>
								<div style="padding-left:25px;">
									<input type="radio" name="option-after_login_redirect" value="wp_default"<?php if($used_redirect == 'wp_default') echo ' checked="checked"';?>/>&nbsp;defaultní (dle nastavení WordPress)<br/>
									<input type="radio" name="option-after_login_redirect" value="wp_homepage"<?php if($used_redirect == 'wp_homepage') echo ' checked="checked"';?>/>&nbsp;domovskou stránku<br/>
									<input type="radio" name="option-after_login_redirect" value="otherpage"<?php if($used_redirect != 'wp_default' && $used_redirect != 'wp_homepage') echo ' checked="checked"';?>/>&nbsp;jinou:&nbsp;
									<input type="text" name="other_loginredirect_page" value="<?php echo ($used_redirect != 'wp_default' && $used_redirect != 'wp_homepage') ? $used_redirect : '';?>"/>
								</div>
							</td>
						</tr>
						<!-- XXX Dokoncit i toto nastaveni!!! 
						<tr>
							<td colspan="2">
								<input type="checkbox" name="option-enable_simple_user_admin"<?php if($options['enable_simple_user_admin'] == true) echo 'checked="checked"';?>/>&nbsp;
								Povolit pro uživatele e-shopu jednoduché administrační rozhraní s přehledem objednávek
							</td>
						</tr>
						 -->
						<?php if($is_admin):?>
						<tr>
							<th scope="row" style="vertical-align: middle;">
								<input type="checkbox" name="use_custom_login_stylesheet"<?php echo ($options['use_custom_login_stylesheet']==true) ? ' checked="checked"' : '';?>/>&nbsp;
								<label for="option-custom_login_stylesheet">Použít zvláštní styl pro přihlašovací stránku:</label>
							</th>
							<td><input type="text" name="option-custom_login_stylesheet" style="min-width: 300px;" value="<?php echo $options['custom_login_stylesheet'];?>"/></td>
							<!-- TODO Pokud styl neexistuje, tak nabidnout vytvorit defaultni soubor v aktualnim adresari tematu. -->
						</tr>
						<?php endif;?>
					</table>
					<hr/>
					<input type="submit" value="  Uložit " name="settings_save" class="button-primary action" />
				</div>
			</form>
		</div>
<?php
  }
	
	/**
	 * Get total count of available items in our eshop.
	 *
	 * @param boolean $show_br
	 * @return string
	 */
	function get_eshop_items_count($show_br = false)
	{
		$count = odWpEshopPluginDbModel::getEshopItemsCount();
		
		return '<b>Počet DVD titulů:</b> ' . (($show_br === true) ? '<br/>' : '') .
				'v naší prodejně a e-shopu: <a href="' . $this->get_main_page_url() . '">' . $count . '</a>';
	}
	
	/**
	 * Content filter (used for rendering pages of this plugin)
	 * 
	 * @param string $aContent
	 * @return string
	 */
	function content_filter($aContent) 
	{
		$content = $aContent;
		
		if(strpos($content, '[eshop_main_page]') !== false) {
			$main_page = $this->render_main_page();
			
			return str_replace('<p>[eshop_main_page]</p>', $main_page, $content);
		}
		elseif(strpos($content, '[eshop_detail_page]') !== false) {
			$detail_page = $this->render_detail_page();
			
			return str_replace('<p>[eshop_detail_page]</p>', $detail_page, $content);
		}
		elseif(strpos($content, '[eshop_search_results_page]') !== false) {
			$search_results_page = $this->render_search_results_page(); 

			return str_replace('<p>[eshop_search_results_page]</p>', $search_results_page, $content);
		}
		elseif(strpos($content, '[eshop_user_registration_page]') !== false) {
			$registration_page = $this->render_user_registration_page();
			
			return str_replace('<p>[eshop_user_registration_page]</p>', $registration_page, $content);
		}
		elseif(strpos($content, '[eshop_contact_form_page]') !== false) {
			$contactform_page = $this->render_contactform_page();
			
			return str_replace('<p>[eshop_contact_form_page]</p>', $contactform_page, $content);
		}
		elseif(strpos($content, '[eshop_basket_page]') !== false) {
			$basket_page = $this->render_basket_page();

			return str_replace('<p>[eshop_basket_page]</p>', $basket_page, $content);
		}
		
		//return str_replace("<p>?\n", '', $content);
		return $content;
	}
	
	/**
	 * Returns URL to search results page
	 * 
	 * @todo We must firstly get page by ID and then render URL from its object. Not like now!
	 * @return string
	 */
	function get_search_results_page_url()
	{
		$options = $this->get_options();
		
		return get_option('home') . '/?page_id=' . $options['eshop_search_results_page_id'];
	}
	
	/**
	 * Renders search results page
	 * 
	 * @return string
	 */
	function render_search_results_page()
	{
		$search_title      = (isset($_POST['nazev'])) 
		        ? $_POST['nazev'] 
				: ((isset($_GET['nazev'])) ? $_GET['nazev'] : '');
	    $search_title_orig = (isset($_POST['nazev_orig'])) 
		        ? $_POST['nazev_orig'] 
				: ((isset($_GET['nazev_orig'])) ? $_GET['nazev_orig'] : '');
	    $search_director   = (isset($_POST['reziser'])) 
	            ? $_POST['reziser'] 
	            : ((isset($_GET['reziser'])) ? $_GET['reziser'] : '');
	    $search_actor      = (isset($_POST['herec'])) 
	            ? $_POST['herec'] 
	            : ((isset($_GET['herec'])) ? $_GET['herec'] : '');
	    $search_shopno     = (isset($_POST['shopno'])) 
	            ? $_POST['shopno'] 
	            : ((isset($_GET['shopno'])) ? $_GET['shopno'] : '');
	    $search_category   = (isset($_POST['kategorie'])) 
	            ? (($_POST['kategorie'] != '---') ? $_POST['kategorie'] : '') 
	            : ((isset($_GET['kategorie'])) ? $_GET['kategorie'] : '');
		
	    $search_title = (empty($search_title)) ? null : $search_title;
	    $search_title_orig = (empty($search_title_orig)) ? null : $search_title_orig;
	    $search_director = (empty($search_director)) ? null : $search_director;
	    $search_actor = (empty($search_actor)) ? null : $search_actor;
	    $search_snopno = (empty($search_shopno)) ? null : $search_shopno;
	    $search_category = (empty($search_category)) ? null : $search_category;
	    
	    $founded_count = odWpEshopPluginDbModel::getEshopItemsBySearchCount(
	        $search_title, 
	        $search_title_orig, 
	        $search_director, 
	        $search_actor,
	        $search_shopno, 
	        $search_category
	    );
		
		$pager = new odWpEshopPluginPager($founded_count, OD_ESHOP_PAGER_ITEMS_LIMIT);
		
		$eshop_items = odWpEshopPluginDbModel::getEshopItemsBySearch(
		    $search_title, 
		    $search_title_orig, 
		    $search_director, 
		    $search_actor, 
		    $search_shopno, 
		    $search_category, 
		    $pager
		);
		
		//$c = (int) $founded_count;
		$c = count($eshop_items);
		$t = '';
		if($c == 0) {
		    $t = 'Litujeme, ale zadání neodpovídá žádná položka. Zkuste vyhledávat podle jiných parametrů.';
		} else if($c == 1) {
		    $t = 'Nalezena <strong>1</strong> odpovídající položka.';
		} else if($c > 1 && $c < 5) {
		    $t = 'Nalezeny <strong>' . $c . '</strong> odpovídající položky.';
		} else {
		    $t = 'Nalezeno <strong>' . $c . '</strong> odpovídajících položek.';
		}
		
		$url = $this->get_search_results_page_url() . 
				((!is_null($search_title)) ? '&amp;nazev=' . $search_title : '') . 
				((!is_null($search_director)) ? '&amp;reziser=' . $search_director: '') . 
				((!is_null($search_actor)) ? '&amp;herec=' . $search_actor : '') . 
				((!is_null($search_shopno)) ? '&amp;shopno=' . $search_shopno : '') . 
				((!is_null($search_category)) ? '&amp;kategorie=' . $search_category: '');
		
		$pager->setUrlPrefix($url);	
?>
        <h2>Výsledky vyhledávání</h2>
        <p><?php echo $t;?></p>
<?php 
        odWpEshopPluginRenderer::renderEshopItems($eshop_items, true, $pager);
	}
	
	/**
	 * Returns URL to user registration page
	 * 
	 * @todo We must firstly get page by ID and then render URL from its object. Not like now!
	 * @return string
	 */
	function get_user_registration_page_url()
	{
		$options = $this->get_options();
		
		return get_option('home') . '/?page_id=' . $options['eshop_user_registration_page_id'];
	}
	
	/**
	 * Renders user registration page
	 * 
	 * @return void
	 */
	function render_user_registration_page()
	{
		include dirname(dirname(dirname(dirname(__FILE__)))) . DIRECTORY_SEPARATOR .
				'wp-includes' . DIRECTORY_SEPARATOR . 'registration.php';
		
		global $wpdb;
		
		$login = '';
		$heslo = '';
		$jmeno = '';
		$prijmeni = '';
		$ulice = '';
		$mesto = '';
		$psc = '';
		$telefon = '';
		$err_msgs = array();
		
		if(isset($_POST['register_user'])) {
			$login = $_POST['login'];
			$heslo = $_POST['heslo'];
			$jmeno = $_POST['jmeno'];
			$prijmeni = $_POST['prijmeni'];
			$email = $_POST['email'];
			$ulice = $_POST['ulice'];
			$mesto = $_POST['mesto'];
			$psc = $_POST['psc'];
			$telefon = $_POST['telefon'];
			
			if(odWpEshopPluginDbModel::checkIfLoginExists($login)) {
				$err_msgs[] = 'Zadané přihlašovací jméno je již použito, prosíme, zvolte jiné.';
			} 
			else if(empty($heslo) || empty($jmeno) || empty($prijmeni) || empty($ulice) || 
			        empty($email) || empty($mesto) || empty($psc) || empty($telefon)) {
				$err_msgs[] = 'Některé z povinných položek nejsou vyplněné - napravte, prosíme, ' . 
				              'tento stav a odešlete formulář znovu.';
			}
			else if(!isset($_POST['podminky'])) {
				$err_msgs[] = 'Nepotvrdili jste souhlas s obchodními podmínkami.';
			}
			
			if(count($err_msgs) == 0) {
				$userdata = array(
						'ID'         => '',
						'user_login' => $login,
						'user_pass'  => $heslo,
						'user_nicename' => '',
						'user_url' => '',
						'user_email' => $email,
						'display_name' => '',
						'nickname' => '',
						'first_name' => $jmeno,
						'last_name' => $prijmeni,
						'description' => '',
						'rich_editing' => 'false',
						'comments_shortcuts' => 'true',
						'admin_color' => 'fresh',
						'use_ssl' => 0,
						'jabber' => '',
						'aim' => '',
						'yim' => '',
						'user_registered' => ''
				);
				$wp_user_id = wp_insert_user($userdata);
				
				$query = "
						INSERT INTO `{$wpdb->prefix}eshop_users`
							( `ID` , `wp_user_ID` , `street` , `town` , `zip` , `phone` , `permition` )
						VALUES
							( NULL , '{$wp_user_id}' , '{$ulice}' , '{$mesto}' , '{$psc}' , '{$telefon}', 1 );";
				$res = $wpdb->query($query);
				$user_id = $wpdb->insert_id;
				
				if($res) {
					// Send email to the user!!!
					$body = "
REGISTRACE  UŽIVATELE
=====================

Zaregistrovali jste se na elektronickém obchodu KingDVD (http://www.kingdvd.cz/).

Pro přihlášení použijte tyto údaje:
  Přihlašovací jméno: {$login}
  Heslo: {$heslo}

Děkujeme, za Vaše zaregistrování. Přejeme mnoho úspěšných nákupů.

Tým www.kingdvd.cz
";
					@wp_mail($email, 'KingDVD - registrace uzivatele', $body, OD_ESHOP_DEFAULT_MAIL_HEADERS, null);
?>
      <p style="font-weight: bold;">Vaše registrace proběhla úspěšně. Email s přihlašovacími údaji byl zaslán na váš e-mail.</p>
<?php
				} else {
?>
      <p style="font-weight: bold;">Litujeme, ale Vaše registrace neproběhla úspěšně!</p>
<?php
				}
				
				return;
			}
		}
?>
		<form action="<?php echo $this->get_user_registration_page_url();?>" method="post">
			<?php foreach($err_msgs as $message):?>
				<p><strong><?php echo $message;?></strong></p>
			<?php endforeach;?>
			<div class="prihlasit">
				<div class="levacast">
					<h2>Nový uživatel:</h2>
					<label for="login">login: *</label>
					<input type="text" name="login" id="login" value="<?php echo $login;?>"/><br/>
					<label for="heslo">heslo: *</label>
					<input type="password" name="heslo" id="heslo" value="<?php echo $heslo;?>"/><br/>
					<label for="jmeno">jméno: *</label>
					<input type="text" name="jmeno" id="jmeno" value="<?php echo $jmeno;?>"/><br/>
					<label for="prijmeni">příjmení: *</label>
					<input type="text" name="prijmeni" id="prijmeni" value="<?php echo $prijmeni;?>"/><br/>
					<label for="ulice">ulice: *</label>
					<input type="text" name="ulice" id="ulice" value="<?php echo $ulice;?>"/><br/>
					<label for="mesto">město: *</label>
					<input type="text" name="mesto" id="mesto" value="<?php echo $mesto;?>"/><br/>
					<label for="psc">PSČ: *</label>
					<input type="text" name="psc" id="psc" value="<?php echo $psc;?>"/><br/>
					<label for="email">email: *</label>
					<input type="text" name="email" id="email" value="<?php echo $email;?>"/><br/>
					<label for="telefon">telefon: *</label>
					<input type="text" name="telefon" id="telefon" value="<?php echo $telefon;?>" /><br/>
					<label for="podminky"><input type="checkbox" name="podminky" id="podminky" class="check"/></label>
					<span class="podminka">souhlasím s <a href="<?php echo get_bloginfo('home');?>/podminky.html" target="_blank">obchodními podmínkami</a></span>
					<input type="submit" name="register_user" value="Přihlásit" class="odeslat" />
				</div>
				<div class="pravacast">
					<h2>Poznámka</h2>
					<p>*) Takto označená pole je nezbytné vyplnit</p>
					<p>&nbsp;</p>
					<p>Pokud jste již registrovaným zákazníkem, <a href="http://www.kingdvd.cz/wp-login.php">přihlášte se</a> prosím a můžete pokračovat ve svém nákupu.</p>
				</div>
			</div>
		</form>
<?php
	}
	
	/**
	 * Returns URL to contact form page
	 * 
	 * @todo We must firstly get page by ID and then render URL from its object. Not like now!
	 * @return string
	 */
	function get_contactform_page_url()
	{
		$options = $this->get_options();
		
		return get_option('home') . '/?page_id=' . $options['eshop_contact_form_page_id'];
	}
	
	/**
	 * Renders contact form page
	 * 
	 * @return void
	 */
	function render_contactform_page()
	{
	    global $wpdb;
	    
		if(isset($_POST['ask_sent'])) {
		    $sender_name = $_POST['jmeno'];
		    $sender_mail = $_POST['email'];
		    $sender_phone = $_POST['telefon'];
		    $question = $_POST['dotaz'];
		    
		    $query = "INSERT INTO `{$wpdb->prefix}eshop_faq` ( `sender_name` , `sender_mail` , `sender_phone` , `question` ) " . 
		            "VALUES ( '{$sender_name}' , '{$sender_mail}' , '{$sender_phone}' , '{$question}' ) ";
		    $wpdb->query($query);
		    
		    $title = 'Dotaz z www.kingdvd.cz';
		    $body = "{$title}\n" . 
		            "======================\n\n" . 
		            "ODESILATEL\n" . 
		            "==========\n" . 
		            "  Jmeno   :    {$sender_name}\n" . 
		            "  E-mail  :    {$sender_mail}\n" . 
		            "  Telefon :    {$sender_phone}\n\n" . 
		            "OTAZKA\n" . 
		            "======\n" . 
		            "{$question}\n";
		    
		   // @wp_mail('honza.kocourek@centrum.cz', $title, $body, ESHOP_DEFAULT_MAIL_HEADERS);
		   // @wp_mail('ondrejd@gmail.com', $title, $body, ESHOP_DEFAULT_MAIL_HEADERS);
      @wp_mail('info@kingdvd.cz', $title, $body, OD_ESHOP_DEFAULT_MAIL_HEADERS);
?>
      <p style="font-weight: bold;">Vaše otázka byla úspěšně odeslána.</p>
<?php
		}
		else {
?>
			<form action="<?php echo $this->get_contactform_page_url();?>" method="post">
					<div class="prihlasit">
							<div class="levacast">
									<h2>Váš dotaz:</h2>
									<label for="jmeno">jméno: *</label>
									<input type="text" name="jmeno" id="jmeno" value="" /><br/>
									<label for="email">email: *</label>
									<input type="text" name="email" id="email" value="" /><br/>
									<label for="telefon">telefon: </label>
									<input type="text" name="telefon" id="telefon" value="" /><br/>
									<label for="dotaz">dotaz: *</label>
									<textarea name="dotaz" id="dotaz"></textarea>
									<input type="submit" name="ask_sent" value="Odeslat" class="odeslat" />
							</div>
							<div class="pravacast">
									<h2>Poznámka</h2>
					<p>*) Takto označená pole je nezbytné vyplnit</p>
					<p>&nbsp;</p>
					<p>Pokud jste již registrovaným zákazníkem, <a href="http://www.kingdvd.cz/wp-login.php">přihlášte se</a> prosím a můžete pokračovat ve svém nákupu.</p>
							</div>
					</div>
			</form>
<?php
    	}
	}
	
	/**
	 * Returns URL to eshop main page
	 * 
	 * @todo OD: We must firstly get page by ID and then render URL from its object. Not like now!
	 * @return string
	 */
	function get_main_page_url()
	{
		$options = $this->get_options();
		
		return get_option('home') . '/?page_id=' . $options['eshop_main_page_id'];
	}
	
	/**
	 * Renders eshop main page
	 * 
	 * @return void
	 */
	function render_main_page()
	{
		$options = $this->get_options();
		$sel_cat_id = (isset($_GET['cat_id'])) ? $_GET['cat_id'] : null;
		$sel_cat = null;
		$sel_char = (isset($_GET['selchar'])) ? $_GET['selchar'] : null;
		$text_page_id = '';
		$text_page = null;
		$eshop_items = array();
		$profile = '';
		$total_items_count = 0;
		$pager = null;
		
		if(!is_null($sel_cat_id)) {
			$sel_cat = odWpEshopPluginDbModel::getGenreCategory($sel_cat_id);
			$total_items_count = odWpEshopPluginDbModel::getEshopItemsByCategoryCount($sel_cat_id);
			$pager = new odWpEshopPluginPager($total_items_count, OD_ESHOP_PAGER_ITEMS_LIMIT);
			$eshop_items = odWpEshopPluginDbModel::getEshopItemsByCategory($sel_cat_id, $pager);
			$profile = 'category';
		} 
		else if(!is_null($sel_char)) {
			$total_items_count = odWpEshopPluginDbModel::getEshopItemsByFirstCharCount($sel_char);
			$pager = new odWpEshopPluginPager($total_items_count, OD_ESHOP_PAGER_ITEMS_LIMIT);
			$eshop_items = odWpEshopPluginDbModel::getEshopItemsByFirstChar($sel_char, $pager);
			$profile = 'char_category';	
		}
		else {
			$text_page_id = $options['eshop_main_page_text_id'];
			$text_page = get_post($text_page_id);
			$eshop_items = odWpEshopPluginDbModel::getEshopItems(12);
			$profile = 'categories';
		}
		
		if($profile == 'categories') {
			if(!is_null($text_page)) {
				echo '<div>' . $text_page->post_content . '</div>';
			}
			
			odWpEshopPluginRenderer::renderGenreCategories($sel_cat);
			odWpEshopPluginRenderer::renderCharCategories($sel_char);
			odWpEshopPluginRenderer::renderEshopItems($eshop_items, false, null);
		}
		else {
			$urlbase = $this->get_main_page_url() . '&amp;';
			
			if($profile == 'category') {
				odWpEshopPluginRenderer::renderGenreCategories($sel_cat);
				$pager->setUrlPrefix($urlbase . 'cat_id=' . $sel_cat_id);
			} else {
				odWpEshopPluginRenderer::renderCharCategories($sel_char);
				$pager->setUrlPrefix($urlbase . 'selchar=' . $sel_char);
			}
			
			odWpEshopPluginRenderer::renderEshopItems($eshop_items, true, $pager);
		}
	}
	
	/**
	 * Returns URL to eshop main page
	 *
	 * @todo We must firstly get page by ID and then render URL from its object. Not like now!
	 * @param integer $aItemId
	 * @return string
	 */
	function get_detail_page_url($aItemId)
	{
		$options = $this->get_options();
		
		return get_option('home') . '/?page_id=' . $options['eshop_detail_page_id'] . '&amp;item_id=' . $aItemId;
	}
	
	/**
	 * Renders eshop detail page
	 *
	 * @return void
	 */
	function render_detail_page()
	{
		$current_user = wp_get_current_user();
		$item_id = (isset($_GET['item_id'])) ? $_GET['item_id'] : null;
		$item = odWpEshopPluginDbModel::getEshopItemById($item_id);
		
		if(!$item) {
?>
			<div class="detail">
				<p><strong>Omlouváme se, ale požadovaný výrobek nebyl nalezen!</strong></p>
			</div>
<?php
		} else {
?>
			<div class="detail">
				<span class="obrazek"><a href="<?php echo $item['image_url1'];?>" rel="lightbox[detail]" title="<?php echo $item['item_title'];?>"><img src="<?php echo $item['image_url2'];?>" alt="<?php echo $item['item_title'];?>" /></a></span>
				<span class="text">
					<table width="100%" border="0" cellspacing="0" cellpadding="0">
					<tr>
						<th class="prvni">Název filmu:</th>
						<th class="druha"><b><?php echo $item['item_title'];?></b></th>
					</tr>
					<tr>
						<th class="prvni">Orig. název:</th>
						<th class="druha"><b><?php echo $item['item_title_orig'];?></b></th>
					</tr>
					<tr>
						<td>Kategorie:</td>
						<td><?php echo $item['genre_categories'];?></td>
					</tr>
					<tr>
						<td>Režisér:</td>
						<td><?php echo $item['item_director'];?></td>
					</tr>
					<tr>
						<td>Herec / série:</td>
						<td><?php echo $item['item_actor'];?></td>
					</tr>
					<tr>
						<td>Jazyk:</td>
						<td><?php echo $item['item_language'];?></td>
					</tr>
					<tr>
						<td>Titulky:</td>
						<td><?php echo $item['item_subtitles'];?></td>
					</tr>
					<tr>
						<td>Číslo DVD:</td>
						<td><?php echo $item['item_shopno'];?></td>
					</tr>
					</table>
				</span>
				<span class="koupit">
				    <?php if($item['prize_value'] == '0' || $item['prize_value'] == ''):?>
					<p>Cena:&nbsp;<span style="font-size: 120%;"><?php echo $item['prize_category'];?></span></p>
				    <?php else:?>
					<p>Cena:&nbsp;<span><?php echo $item['prize_value'];?></span>&nbsp;Kč</p>
					<?php endif;?>
					<?php if($current_user->has_cap('customer')):?>
					<a href="<?php echo $this->get_basket_page_url($item['item_ID']);?>" class="tlacitko">Přidat DVD do košíku</a>
					<?php else:?>
					<a href="<?php echo $this->get_user_registration_page_url();?>" class="tlacitko" style="opacity: 0.6;">Nejste přihlášen</a>
					<?php endif;?>
				</span>
			</div>
<?php
		}
	}
	
	/**
	 * Returns URL to eshop basket page
	 * 
	 * @todo We must firstly get page by ID and then render URL from its object. Not like now!
	 * @param integer $aItemId (Optional) ID of eshop item we want to add into the basket.
	 * @return string
	 */
	function get_basket_page_url($aItemId = null)
	{
		$options = $this->get_options();
		$url = get_option('home') . '/?page_id=' . $options['eshop_basket_page_id'];
		
		if(is_null($aItemId)) {
			return $url;
		}
		
		return $url . '&amp;item_id=' . $aItemId;
	}
	
	/**
	 * Renders eshop basket page
	 * 
	 * @return void
	 */
	function render_basket_page()
	{
		$current_user = wp_get_current_user();
		$message = '';
		
		if(!$current_user->has_cap('customer')) {
?>
		    <div class="kosik">
		        <p>Aby jste mohli nakupovat v našem elektronickém obchodě, musíte 
		        být přihlášeným uživatelem!</p>
            </div>
<?php
            return;
		}
		
		if(isset($_GET['item_id'])) {
			$item_id = (int) $_GET['item_id'];
			
			$message = ($this->add_item_to_basket($item_id, 1, $current_user->ID)) 
					? 'Položka byla úspěšně přidána do košíku.' 
					: 'Litujeme, ale položka nebyla úspěšně přidána do košíku.';
		}
		
		$prepare_finish_order = false;
		$finish_order = false;
		$order_finished = false;
		
		if(isset($_GET['op'])) {
			$op = $_GET['op'];
			
			if($op == 'remove') {
				$order_item_id = (int) $_GET['order_item_id']; 
				
				$message = (odWpEshopPluginDbModel::removeOrderItem($order_item_id)) 
						? 'Položka byla úspěšně odstraněna z košíku.' 
						: 'Litujeme, ale položka nebyla úspěšně odstraněna z košíku.';
			}
			else if($op == 'prepare_finish_order') {
				$prepare_finish_order = true;
			}
		}
		
		$current_order = odWpEshopPluginDbModel::getCurrentOrderForUser($current_user->ID);
		
		if(isset($_POST['finish_order'])) {
			// Zobrazime kompletni objednavku (tak jak pujde emailem) a tlacitko "Skutecne odeslat".
			$delivery_type = $_POST['delivery_type'];
			
			$values = array('delivery' => $delivery_type);
			odWpEshopPluginDbModel::updateOrder($current_order->order_ID, $values);
			$current_order = odWpEshopPluginDbModel::getCurrentOrderForUser($current_user->ID);
			
			$finish_order = true;
		}
		
		if(isset($_POST['finish_order2'])) {
			// Odesleme objednavku (pak uzavreme aktualni a vytvorime novou).
			$order_finished = $this->finish_eshop_order($current_order);
		}
		
?>
		<div class="kosik">
			<?php if($message != ''):?>
			<p><strong><?php echo $message;?></strong></p>
			<?php endif;?>
			<?php if($order_finished === true)/* Objednavka hotova */:?>
				<p>Vaše objednávka byla úspěšně odeslána. Vyřízena bude do 14 dnů.</p>
			<?php elseif($finish_order === true)/* Prehled objednavky pred odeslanim. */:?>
			<form action="<?php echo $this->get_basket_page_url();?>" method="post">
				<p>Chystáte se odeslat následující objednávku:</p>
				<span class="text">
					<table width="100%" border="0" cellspacing="0" cellpadding="0">
						<tr>
							<th colspan="3">PŘEHLED POLOŽEK:</th>
						</tr>
						<?php foreach($current_order->order_items as $order_item):?>
						<?php $total_prize = $total_prize + ((int) $order_item->eshop_item_prize_category_prize * (int) $order_item->order_item_count);?>
						<tr>
							<th class="prvni">Název filmu:</th>
							<td class="druha">
								<strong><?php echo $order_item->eshop_item_title;?>&nbsp;</strong>
								(č.: <code><?php echo $order_item->eshop_item_shopno;?></code>)
							</td>
							<td class="treti" style="min-width: 70px;"><?php echo $order_item->eshop_item_prize_category_prize;?>&nbsp;Kč</td>
						</tr>
						<?php endforeach;?>
						<tr class="celkem">
							<th class="prvni">CELKEM:</th>
							<th class="druha">&nbsp;</th>
							<th class="treti" style="min-width: 70px;"><?php echo $current_order->order_total_prize;?> Kč</th>
						</tr>
						<tr>
							<td colspan="3"> &nbsp;</td>
						</tr>
						<tr>
							<th class="prvni">DOPRAVA:</th>
							<td class="druha"><?php echo ($current_order->order_delivery == 'postoffice') ? 'Dobírkou (Česká pošta)' : 'Osobní odběr (prodejna Praha)';?></td>
							<td class="treti" style="min-width: 70px;"><?php echo $current_order->order_delivery_prize;?>&nbsp;Kč</td>
						</tr>
						<tr class="celkem">
							<th class="prvni">CELKEM:</th>
							<th class="druha">&nbsp;</th>
							<th class="treti" style="min-width: 70px;"><?php echo $current_order->order_total_prize_with_delivery;?>&nbsp;Kč</th>
						</tr>
					</table>
				</span>
				<span class="koupit">
					<input type="submit" name="finish_order2" value="Odeslat objednávku" class="tlacitko"/>
				</span>
			</form>
			<?php elseif($prepare_finish_order === true)/* Odesilani objednavky. Zvolit typ dodavatele. */:?>
			<form action="<?php echo $this->get_basket_page_url();?>" method="post">
				<span class="text">
					<p>
						Vyberte způsob dodání:&nbsp;
						<select name="delivery_type" value="personal">
							<option value="postoffice" selected="selected">dobírkou (Česká pošta, 95 Kč)</option>
							<option value="personal">osobní odběr (prodejna Praha)</option>
						</select>
					</p>
				</span>
				<span class="koupit">
					<input type="submit" name="finish_order" value="Odeslat objednávku" class="tlacitko"/>
				</span>
			</form>
			<?php else/* Seznam objednavek */:?>
			<span class="text">
				<table width="100%" border="0" cellspacing="0" cellpadding="0">
					<?php if(count($current_order->order_items) == 0):?>
					<tr>
						<th colspan="3">Váš košík je momentálně prázdný.</th>
					</tr>
					<?php else:?>
					<?php foreach($current_order->order_items as $order_item):?>
					<?php $total_prize = $total_prize + ((int) $order_item->eshop_item_prize_category_prize * (int) $order_item->order_item_count);?>
					<tr>
						<th class="prvni">Název filmu:</th>
						<th class="druha"><?php echo $order_item->eshop_item_title;?></th>
						<th class="treti"><?php echo $order_item->eshop_item_prize_category_prize;?>&nbsp;Kč</th>
						<th class="ctvrta"><a href="<?php echo $this->get_basket_page_url();?>&amp;op=remove&amp;order_item_id=<?php echo $order_item->order_item_ID;?>">odstranit</a></th>
					</tr>
					<?php endforeach;?>
					<tr class="celkem">
						<th class="prvni">CELKEM:</th>
						<th class="druha">&nbsp;</th>
						<th class="treti"><?php echo $total_prize;?> Kč</th>
						<th class="ctvrta">&nbsp;</th>
					</tr>
					<?php endif;?>
				</table>
			</span>
			<span class="pokracovat">
				<a href="<?php echo $this->get_main_page_url();?>" class="tlacitko">Pokračovat v nákupu</a>
			</span>
			<?php if(count($current_order->order_items) > 0):?>
			<span class="koupit">
				<a href="<?php echo $this->get_basket_page_url();?>&amp;op=prepare_finish_order" class="tlacitko">Dokončit objednávku</a>
			</span>
			<?php endif;?>
			<?php endif;?>
		</div>
<?php		
	}
	
	/**
	 * Adss eshop item to the basket (for the current user or for user with given WP ID).
	 * 
	 * @param integer $aItemId
	 * @param integer $aCount
	 * @param integer $aWpUserId
	 * @return boolean
	 */
	function add_item_to_basket($aItemId = null, $aCount = 1, $aWpUserId = null) 
	{
		if(is_null($aItemId)) {
			return false;
		}
		
		if(is_null($aWpUserId)) {
			$current_user = wp_get_current_user();
			$aWpUserId = $current_user->ID;
		}
		
		$current_order = odWpEshopPluginDbModel::getCurrentOrderForUser($aWpUserId);
		
		if(is_null($current_order)) {
			return false;
		}
		
		return odWpEshopPluginDbModel::addOrderItem($current_order->order_ID, $aItemId, $aCount);
	}
	
	/**
	 * ...
	 *
	 * @param object $aOrder
	 * @return string
	 */
	function get_message_for_order($aOrder = null, $aDate = null)
	{
		$current_date = (is_null($aDate)) ? $aOrder->order_finished_when : $aDate;
		$user_fullname = $aOrder->order_wpuser->last_name . ', ' . $aOrder->order_wpuser->first_name; 
		$delivery = ($aOrder->order_delivery == 'postoffice')
				? 'dobírkou (Česká pošta)' 
				: 'osobní odběr';
		
		$mail_msg = "
OBJEDNÁVKA Č. {$aOrder->order_ID}
=================


OBJEDNAVATEL
============

Jméno: {$user_fullname}
Ulice: {$aOrder->order_user_street}
Město: {$aOrder->order_user_town}
PSČ: {$aOrder->order_user_zip}
Tel.: {$aOrder->order_user_phone}


PŘEHLED POLOŽEK
===============\n\n";
		
		foreach($aOrder->order_items as $order_item) {
			$mail_msg .= "{$order_item->eshop_item_shopno}, {$order_item->eshop_item_title}, {$order_item->eshop_item_prize_category_prize} Kč\n";
		}
		
		$mail_msg .= "---------------------
Celková cena: {$aOrder->order_total_prize} Kč


SOUHRN
======
Čas vytvoření: {$current_date}
Typ dopravy: {$delivery}, {$aOrder->order_delivery_prize} Kč
Souhrnná cena: {$aOrder->order_total_prize_with_delivery} Kč\n";
		
		return $mail_msg;
	}
	
	/**
	 * Finish given order (order email and finish order in database).
	 * 
	 * @param object $aOrder
	 * @return boolean
	 */
	function finish_eshop_order($aOrder = null)
	{
		if(is_null($aOrder)) {
			return false;
		}
		
		$current_date = date('Y-m-d, H:i:s');
		$mail_msg = $this->get_message_for_order($aOrder, $current_date);
		$title = 'Objednávka - ID ' . $aOrder->order_ID;
		//@wp_mail('honza.kocourek@centrum.cz', $title, $mail_msg, OD_ESHOP_DEFAULT_MAIL_HEADERS);
		//@wp_mail('ondrejd@gmail.com', $title, $mail_msg, OD_ESHOP_DEFAULT_MAIL_HEADERS);
		@wp_mail('info@kingdvd.cz', $title, $mail_msg, OD_ESHOP_DEFAULT_MAIL_HEADERS);
    
		// XXX 'finished_when'!!!
		$values = array('finished' => '1', 
		                'finished_when' => null);
		odWpEshopPluginDbModel::updateOrder($aOrder->order_ID, $values);
		
		return true;
	}
	
	// ===========================================================================
	// These are for e-shop basket and user session self
	
	/**
	 * Is currently logged any user?
	 * 
	 * @return boolean
	 */
	function is_user() 
	{
		$current_user = wp_get_current_user();
	    
		if(!($current_user instanceof WP_User)) {
			return false;
		}
		
		if($current_user->ID == 0 || !$current_user->has_cap('customer')) {
			return false;
		}
		
	    return true;
	}
	
	/**
	 * Returns full name of the current user.
	 * 
	 * @return string
	 */
	function get_current_user_fullname()
	{
		$current_user = wp_get_current_user();
		
		if(empty($current_user->first_name)) {
			if(empty($currect_user->last_name)) {
				return '';	
			}
			
			return $current_user->last_name;
		}
		
		return $current_user->last_name . ', ' . $current_user->first_name;
	}
	
	/**
	 * Returns count of all items that are in the eshop basket of the current user.
	 * 
	 * @return integer
	 */
	function get_basket_items_count() 
	{
	    $current_user = wp_get_current_user();
	    $current_order = odWpEshopPluginDbModel::getCurrentOrderForUser($current_user->ID);
	    
	    return $current_order->order_items_count;
	}
	
	// ===========================================================================
	// These below are meaned as 'private' 
	
	/**
	 * Handle image upload.
	 * 
	 * @param array $aImage Proper $_FILES value.
	 * @return string|boolean Returns new image file name or FALSE
	 */
	function _upload_image($aImage)
	{
		if($aImage['name'] == '') {
			return false;
		}
		
		// We allow only JPEG images
		$ext = strtolower(strrchr($aImage['name'], '.')); 
		
		if($ext != '.jpg') {
	?>
			<div id="message" class="error fade">
				<p><strong>Nahrávat můžete pouze obrázky typu <code>JPEG</code>!</strong></p>
			</div>
	<?php
			return false;
		}
		
		$filename = md5(uniqid(mt_rand(), true)) . '.jpg';
		$uploaddir = dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR . 'eshop_images';
		$uploadfile = $uploaddir . DIRECTORY_SEPARATOR . $filename;
		
		// XXX Check `max_upload_filesize` value!!!
		if(!move_uploaded_file($aImage['tmp_name'], $uploadfile)) {
			return false;
		}
		
		$this->_resize_image($uploadfile, str_replace('.jpg', OD_ESHOP_THUMB_SUFFIX_ORIGINAL, $uploadfile), OD_ESHOP_THUMB_HEIGHT_ORIGINAL);
		$this->_resize_image($uploadfile, str_replace('.jpg', OD_ESHOP_THUMB_SUFFIX_NORMAL, $uploadfile), OD_ESHOP_THUMB_HEIGHT_NORMAL);
		$this->_resize_image($uploadfile, str_replace('.jpg', OD_ESHOP_THUMB_SUFFIX_SMALL, $uploadfile), OD_ESHOP_THUMB_HEIGHT_SMALL);
		
		return $filename;
	}
	
	/**
	 * Resize given image to the specified height.
	 *
	 * @param string $aImage
	 * @param string $aNewImage
	 * @param integer $aToHeight
	 * @return void
	 */
	function _resize_image($aImage, $aNewImage, $aToHeight)
	{
		list($imagewidth, $imageheight) = getimagesize($aImage);
		$scale = $imageheight / (int) $aToHeight;
		$new_width = round($imagewidth * (1 / $scale));
		$new_height = round($imageheight * (1 / $scale));
		
		$image_resized = imagecreatetruecolor($new_width, $new_height);
		$image_tmp = imagecreatefromjpeg($aImage);
		imagecopyresampled($image_resized, $image_tmp, 0, 0, 0, 0, $new_width,
											 $new_height, $imagewidth, $imageheight);
		
		imagejpeg($image_resized, $aNewImage);
		imagedestroy($image_resized);
	}
	
}

// ===========================================================================
// Plugin initialization

global $od_eshop_wpplugin;

$od_eshop_wpplugin = new odEshopWpPlugin();
